Swift之实现表格UITableView数据首字母顺序排列展示并添加“索引”快速定位查找功能

整理数据
  • 获取汉字拼音的首字母
/*
 *获取汉字拼音的首字母, 返回的字母是大写形式, 例如: @"俺妹", 返回 @"A".
 *如果字符串开头不是汉字, 而是字母, 则直接返回该字母, 例如: @"b美女", 返回 @"B".
 *如果字符串开头不是汉字和字母, 则直接返回 @"#", 例如: @"&哈哈", 返回 @"#".
 *字符串开头有特殊字符(空格,换行)不影响判定, 例如@"   a啦啦啦", 返回 @"A".
 */
 - (NSString *)getFirstLetter {
    NSString *words = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (words.length == 0) {
        return nil;
    }
    NSString *result = nil;
    unichar firstLetter = [words characterAtIndex:0];
    
    int index = firstLetter - HANZI_START;
    if (index >= 0 && index <= HANZI_COUNT) {
        result = [NSString stringWithFormat:@"%c", firstLetterArray[index]];
    } else if ((firstLetter >= 'a' && firstLetter <= 'z')
               || (firstLetter >= 'A' && firstLetter <= 'Z')) {
        result = [NSString stringWithFormat:@"%c", firstLetter];
    } else {
        result = @"#";
    }
    return [result uppercaseString];
}
  • 将一个字符串数组按照拼音首字母规则进行重组排序, 返回重组后的数组
/*
 *将一个字符串数组按照拼音首字母规则进行重组排序, 返回重组后的数组.
 *格式和规则为:
 
  [
      @{
           @"firstLetter": @"A",
           @"content": @[@"啊", @"阿狸"]
       }
      ,
      @{
           @"firstLetter": @"B",
           @"content": @[@"部落", @"帮派"]
       }
      ,
      ...
  ]
 
 *只会出现有对应元素的字母字典, 例如: 如果没有对应 @"C"的字符串出现, 则数组内也不会出现 @"C"的字典.
 *数组内字典的顺序按照26个字母的顺序排序
 *@"#"对应的字典永远出现在数组最后一位
 */
 - (NSArray *)arrayWithPinYinFirstLetterFormat {
    if (![self count]) {
        return [NSMutableArray array];
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[NSMutableArray array] forKey:@"#"];
    for (int i = 'A'; i <= 'Z'; i++) {
        [dict setObject:[NSMutableArray array]
                 forKey:[NSString stringWithUTF8String:(const char *)&i]];
    }
    
    for (NSDictionary *dic in self) {
        NSString *words = dic[@"title"];
        NSString *firstLetter = [words getFirstLetter];
        NSMutableArray *array = dict[firstLetter];
        [array addObject:dic];
    }
    
    NSMutableArray *resultArray = [NSMutableArray array];
    for (int i = 'A'; i <= 'Z'; i++) {
        NSString *firstLetter = [NSString stringWithUTF8String:(const char *)&i];
        NSMutableArray *array = dict[firstLetter];
        if ([array count]) {
            [array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                NSString *word1 = obj1[@"title"];
                NSString *word2 = obj2[@"title"];
                return [word1 localizedCompare:word2];
            }];
            
            NSDictionary *resultDict = @{@"firstLetter": firstLetter,
                                         @"content": array};
            [resultArray addObject:resultDict];
        }
    }
    
    if ([dict[@"#"] count]) {
        NSMutableArray *array = dict[@"#"];
        [array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSString *word1 = obj1[@"title"];
            NSString *word2 = obj2[@"title"];
            return [word1 localizedCompare:word2];
        }];
        NSDictionary *resultDict = @{@"firstLetter": @"#",
                                     @"content": array};
        [resultArray addObject:resultDict];
    }
    return resultArray;
}
  • 将没有排序的数组按字母首字母的顺序排列, 生成新的排序数组:
self.firstLitterArray = (self.bankArray! as NSArray).withPinYinFirstLetterFormat() as! [[String:Any]]
UITableView协议
  • 实现UITableViewDelegate,UITableViewDataSource以下的协议:
	func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 35))
        view.backgroundColor = UIColor.init(red: 212/255.0, green: 212/255.0, blue: 212/255.0, alpha: 1)
        let label = UILabel.init(frame: CGRect.init(x: 16, y: 0, width: 15, height: 35))
        label.text = (self.firstLitterArray[section]["firstLetter"] as! String)
        label.textAlignment = .center
        label.textColor = UIColor.init(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1)
        label.font = UIFont.boldSystemFont(ofSize: 14)
        view.addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return (self.firstLitterArray[section]["firstLetter"] as! String)
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        var title : [String] = []
        for i in 0 ..< self.firstLitterArray.count {
            title.append(self.firstLitterArray[i]["firstLetter"] as! String)
        }
        return title
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        if title == UITableView.indexSearch {
            return NSNotFound
        }
        return UILocalizedIndexedCollation.current().section(forSectionIndexTitle: index)
    }
效果展示

在这里插入图片描述

完整示例

Swift之UITableView新增“索引”数组快速定位查找数据

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

╰つ栺尖篴夢ゞ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值