【问题标题】:divided into sections alphabetic my Tableview我的Tableview按字母分成几部分
【发布时间】:2015-02-03 08:36:03
【问题描述】:

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

【问题讨论】:

    标签: ios tableview alphabetical sections divide


    【解决方案1】:

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

    在 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上,代码可能会有小错误,但原理不变

    【讨论】:

    • 我使用objective-c语言。
    • 这很快,给我几分钟,我将编辑我的答案以包含 obj-C
    【解决方案2】:

    问题是 UITableView 及其委托和数据源的一个非常简单的实现。

    实际的解释有点长,所以这里有一个应用程序的教程,它的功能与你想要的非常相似。

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

    【讨论】:

    • 这是我需要的部分,但它没有解释如何按字母顺序从 A 到 Z 划分数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多