分为我的Tableview字母表

时间:2015-02-03 08:36:04

标签: ios tableview alphabetical sections divide

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

2 个答案:

答案 0 :(得分:4)

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

在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]在特定部分中获取行的内容,这将返回一个数组以密钥

中存储的字母开头的所有名称

编辑:夫妇与Piterwilson的回答有一个完整的答案

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

注意:由于我不在我的Mac上,代码中可能存在小错误,但原则仍然相同

答案 1 :(得分:2)

问题是UITableView及其委托和数据源的非常直接的实现。

实际的解释有点长,所以这里是一个应用程序的教程,它可以完成你想要的东西。

http://www.appcoda.com/ios-programming-index-list-uitableview/