从 NSArray 为 UITableView 创建索引
我读过创建索引(uitableview 旁边的 az)的最佳方法是设置一个 nsdictionaries 数组,其中每个字典对应一个部分,并且 rowValue 键包含一个行数组。
NSDictionary
headerTitle => ‘A’
rowValues => {”Aardvark”, “Ape”, “Aquaman”}
NSDictionary
headerTitle => ‘B’
rowValues => {”Bat”, “Boot”, “Bubbles”} etc
但是如何从所有行标题的数组中创建它 - {“Aardvark”,“Ape”,“Aquaman”,“Bat”,“Boot”,“Bubbles”,“Cat”,“Cabbage”等}。 ..?
I've read that the best way of creating an index (the a-z at the side of a uitableview) is to set up an array of nsdictionaries, where each dictionary corresponds to a section, and a rowValue key contains an array of the rows.
NSDictionary
headerTitle => ‘A’
rowValues => {”Aardvark”, “Ape”, “Aquaman”}
NSDictionary
headerTitle => ‘B’
rowValues => {”Bat”, “Boot”, “Bubbles”} etc
But how can this be created from an array of all the row titles - {”Aardvark”, “Ape”, “Aquaman”, ”Bat”, “Boot”, “Bubbles”, "Cat", "Cabbage" etc} ...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最近有一个类似的目标,这就是我解决它的方法。与 Robin 的解决方案相比,它的优点是它根据数组的内容动态创建索引标题数组,并且它不会包含空部分的索引(而且它更干净一些)。
我创建了一个
NSMutableDictionary
类别,它接受一个数据数组作为参数并返回一个NSMutableDictionary
(我们将其称为indexDictionary
,它应该是一个实例变量):类别方法:
然后我创建一个
NSArray
实例变量来排序和存储indexDictionary
中的所有键:您现在已经拥有了设置所需的一切您的索引 桌子。实现以下方法(如果有些内容不言自明,请告诉我):
结果是一个带有索引的表,该索引会跳过没有关联数据的字母。
I recently had a similar objective and this is how I solved it. The advantage of this over Robin's solution is that it creates the index title array dynamically based on the content of your array and it won't include indices for empty sections (plus it's a little cleaner).
I created a category of
NSMutableDictionary
that takes an array of data as a parameter and returns anNSMutableDictionary
(we'll call itindexDictionary
and it should be an instance variable):The category method:
Then I create an
NSArray
instance variable to sort and store all the keys fromindexDictionary
:You now have everything you need to set up the index for your table. Implement the following methods (if something isn't self explanatory, just let me know):
The result is a table with an index that skips letters that have no associated data.
这是我在最近的项目之一中使用的代码。
This is the code that I have used in one of the recent projects.
我正在开发一个项目,我需要同一问题的动态解决方案,所以我找到了这个解决方案,它返回仅包含可用部分的字典。希望它能帮助某人。
I was working on one project where I need dynamic solutions for same problem so I figure out this solutions which returns dictionary with only available sections. Hope it help someone.