gpt4 book ai didi

ios - 我的Tableview按字母分成几部分

转载 作者:行者123 更新时间:2023-12-01 17:30:10 27 4
gpt4 key购买 nike

我有一个包含字符串格式名称的数组(es.luca、marco、giuseppe、..)。
该数组将用于填充表格。
如何将表格划分为部分(az)并将数组的名称放入右侧部分中?

最佳答案

您可以遍历数组以创建一个字典,其中第一个字母作为键,名称数组作为值:

在 swift

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
}
}

在 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];
}
}

然后你可以通过使用 nameDictionary.count 来获取你的部分数,通过获取 nameDictionary[key].count 来获取行数,以及使用 nameDictionary[key] 来获取特定部分中的行内容,这将返回一个包含所有名称的数组以存储在 key 中的字母开头

编辑:将其与 Piterwilson 的答案结合起来,以获得完整的答案

编辑 2 : 添加了 Obj-C 代码

通知:由于我不在我的mac上,代码中可能存在小错误,但原理保持不变

关于ios - 我的Tableview按字母分成几部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294480/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com