Gia*_*rpi 1 alphabetical tableview divide ios sections
我有一个包含字符串格式名称的数组(es.luca,marco,giuseppe,..)。该数组将用于填充表格。如何将表划分为部分(az)并在右侧部分中放入数组的名称?
您可以遍历数组以创建一个以第一个字母为键、一个名称数组为值的字典:
在斯威夫特
var nameDictionary: Dictionary<String, Array<String>> = [:]
for name in nameArray {
var key = name[0].uppercaseString // first letter of the name is the key
if let arrayForLetter = nameDictionary[key] { // if the key already exists
arrayForLetter.append(name) // we update the value
nameDictionary.updateValue(arrayForLetter, forKey: key) // and we pass it to the dictionary
} else { // if the key doesn't already exists in our dictionary
nameDictionary.updateValue([name], forKey: key) // we create an array with the name and add it to the dictionary
}
}
Run Code Online (Sandbox Code Playgroud)
在 Obj-C 中
NSMutableDictionary *nameDictionary = [[NSMutableDictionary alloc] init];
for name in nameArray {
NSString *key = [[name substringToIndex: 1] uppercaseString];
if [nameDictionary objectForKey:key] != nil {
NSMutableArray *tempArray = [nameDictionary objectForKey:key];
[tempArray addObject: name];
[nameDictionary setObject:tempArray forkey:key];
} else {
NSMutableArray *tempArray = [[NSMutableArray alloc] initWithObjects: name, nil];
[nameDictionary setObject:tempArray forkey:key];
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以通过使用 nameDictionary.count 获得你的部分数量,通过获得 nameDictionary[key].count 和你在特定部分中的行内容 nameDictionary[key] 它将返回所有名称的数组以存储在 key 中的字母开头
编辑:结合 Piterwilson 的回答以获得完整的答案
编辑 2:添加了 Obj-C 代码
注意:由于我不在我的 mac 上,代码中可能会有小错误,但原理保持不变
| 归档时间: |
|
| 查看次数: |
2787 次 |
| 最近记录: |