iOS 简单实现UITableView多选的一种方式

前言:

这篇文章可以看到哪些内容 类似于微信通讯录A_Z排序处理, 分区处理, 多行选中处理, 文末留有demo. 需要的话 下载就好.

#import “JTContactDealTool.h” 这个类用来处理汉字转拼音, 首字母排序
@interface JTContactDealTool : NSObject
+ (NSString *)transform:(NSString *)chinese;
+ (NSMutableDictionary *)sortArrayWithPinYin:(NSArray *)list;
@end

#import "JTContactDealTool.h"

@implementation JTContactDealTool
/// 汉字转拼音
+ (NSString *)transform:(NSString *)chinese
{
    if(!chinese){
        return nil;
    }
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    return [pinyin uppercaseString];
}
/// 拿到第一个字母并排序
+ (NSString *)getFirstUpperLetter:(NSString *)chinese {
    NSString *pinyin = [self transform:chinese];
    NSString *firstUpperLetter = [[pinyin substringToIndex:1] uppercaseString];
    if ([firstUpperLetter compare:@"A"] != NSOrderedAscending &&
        [firstUpperLetter compare:@"Z"] != NSOrderedDescending) {
        return firstUpperLetter;
    } else {
        return @"#";
    }
}

+ (NSMutableDictionary *)sortArrayWithPinYin:(NSArray *)list{
    
    NSMutableArray *contentArray = [NSMutableArray array];
    for (int i = 0; i < 26; i++) {
        
        [contentArray addObject:[NSMutableArray array]];
    }
    NSArray *keys = @[
                      @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N",
                      @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", @"#"
                      ];
    NSMutableArray *tempArray = [NSMutableArray array];
    /// 这里我把list里放的是字符串, 实际呢应该是model, 比如model.name 相应改一下就好了 
    for (id user in list) {
        
        NSString *firstLetter;
        firstLetter = [self getFirstUpperLetter:(NSString *)user];
        int asciiIndex = [firstLetter characterAtIndex:0];
        int index = asciiIndex - [@"A" characterAtIndex:0];
        char c = [firstLetter characterAtIndex:0];
        if (isalpha(c) == 0) {
            [tempArray addObject:user];
        }else{
            NSMutableArray *indexArray = [contentArray objectAtIndex:index];
            [indexArray addObject:user];
        }
    }
    
    NSMutableDictionary *infoDic = [NSMutableDictionary dictionary];
    for(int i = 0; i < contentArray.count; i++){
        NSMutableArray *itemArray = [contentArray objectAtIndex:i];
        if(itemArray.count > 0){
            
            if (![itemArray count])
                continue;
            [infoDic setObject:itemArray forKey:keys[i]];
        }
    }
    if ([tempArray count]) [infoDic setObject:tempArray forKey:@"#"];
    
    NSArray *key = [[infoDic allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableArray *allKeys = [[NSMutableArray alloc] initWithArray:key];
    NSMutableDictionary *resultDic = [NSMutableDictionary new];
    [resultDic setObject:infoDic forKey:@"infoDic"];
    [resultDic setObject:allKeys forKey:@"allKeys"];
    return resultDic;
}
@end
VC中创建一个表视图, 并对数据以及逻辑进行处理
#import "ViewController.h"
#import "JTTableViewCell.h"
#import "JTContactDealTool.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *dataDictionary;
@property (nonatomic, strong) NSArray *keys;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, strong) NSMutableDictionary *allValues;

@end

@implementation ViewController
/// 选中的数组
- (NSMutableArray *)selectArray {
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}
/// 初始化视图
- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.allowsMultipleSelection = YES;
        [_tableView registerClass:[JTTableViewCell class] forCellReuseIdentifier:@"JTTableViewCell"];
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _keys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *key = [self.keys objectAtIndex:section];
    NSArray *arrayValueForKey = [self.allValues objectForKey:key];
    return arrayValueForKey.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 56;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return _keys;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        UIView *sectionHeader = [[UIView alloc] init];
        sectionHeader.backgroundColor = [UIColor yellowColor];
        UILabel *label = [[UILabel alloc] init];
        label.adjustsFontSizeToFitWidth = YES;
        label.frame = CGRectMake(16, 5, 10, 11);
        [sectionHeader addSubview:label];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor blackColor];
        label.text = _keys[section];
        return sectionHeader;
    }else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JTTableViewCell"];
    NSString *key = [self.keys objectAtIndex:indexPath.section];
    NSArray *arrayValueForKey = [self.allValues objectForKey:key];
    cell.titleLabel.text = arrayValueForKey[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.selectArray addObject:[self getCurrentStr:indexPath]];
    NSLog(@"当前选中数组中元素 didSelectRowAtIndexPathSelectArray ==== %@", self.selectArray);
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.selectArray removeObject:[self getCurrentStr:indexPath]];
    NSLog(@"当前选中数组中元素 didDeselectRowAtIndexPathSelectArray ==== %@", self.selectArray);
}

- (NSString *)getCurrentStr:(NSIndexPath *)indexPath {
    NSString *key = [self.keys objectAtIndex:indexPath.section];
    NSArray *arrayValueForKey = [self.allValues objectForKey:key];
    return arrayValueForKey[indexPath.row];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview:self.tableView];
    
    _dataArray = @[@"A01", @"A02", @"A03", @"A04",
                   @"B01", @"B02", @"B03", @"B04",
                   @"C01", @"C02", @"C03", @"C04",
                   @"D01", @"D02", @"D03", @"D04"
                   ];
    self.keys = [JTContactDealTool sortArrayWithPinYin:_dataArray][@"allKeys"];
    self.allValues = [JTContactDealTool sortArrayWithPinYin:_dataArray][@"infoDic"];
    [self.tableView reloadData];
}
自定义cell
#import "JTTableViewCell.h"

@implementation JTTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.selectedImageView = [[UIImageView alloc] init];
        self.selectedImageView.frame = CGRectMake(16, 22, 16, 16);
        [self.contentView addSubview:self.selectedImageView];
        
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.frame = CGRectMake(79, 21, 100, 17);
        [self.contentView addSubview:self.titleLabel];
        
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    if (selected) {
        _selectedImageView.image = [UIImage imageNamed:@"checkmark_round_blueBg"];
    }else {
        _selectedImageView.image = [UIImage imageNamed:@"checkmark_onlyCircle_gray"];
    }

    // Configure the view for the selected state
}

总结: 这里我只是总结了一种多选的实现方案, 分享一下.

在这里插入图片描述

https://github.com/summerxx27/UITableViewMultipleSelectionDemo.git

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值