美文网首页
iOS~ tableview侧边索引栏(如:通讯录右侧拼音栏):

iOS~ tableview侧边索引栏(如:通讯录右侧拼音栏):

作者: 阳光下的叶子呵 | 来源:发表于2022-05-24 23:49 被阅读0次

一、侧边栏 自定义:

1、(如下,系统的侧边索引栏)获取数据二维数组section_cityCollationArray,和字母数组charArray,header可以如下面方法;
2、侧边栏:(自定义),可以使用UICollectionView,在tableview的右侧位置,将点击其itemCelltableview的section相关联起来(通知、或者代理、block等等方法,点击事件、滑动事件(滑动显示带颜色的背景什么的。。。))

相关链接:
(1):UITableView的右侧索引效果
(2):iOS UITableView字母索引——系统自带检索栏

IMG_3835.jpg

二、系统的侧边索引栏:

1、自定义侧边栏的字母个数:( 方法: 处理之后的侧边栏的 字母数组,将没有这个拼音的时候,删除掉)
2、例如方法setupCityCollation,拿到处理好的二维数组section_cityCollationArray、处理好的大写字母数组charArray,header上的字体显示可以找下面或者自定义UILabel的方法,侧边栏是系统的UITableViewIndex,系统的侧边栏不支持自定义。

#import "GW_ClubListHome_CitySelectView.h"
#import "GW_ClubListHome_CitySelectTableHeaderView.h"
#import "GW_ClubListHome_CitySelectViewCell.h"
#import "GW_ClubListHome_SelectCityModel.h"


@interface GW_ClubListHome_CitySelectView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView   *tableView;

@property (nonatomic, strong) UILocalizedIndexedCollation *cityCollation; // 侧边索引栏

@property (nonatomic, strong) GW_ClubListHome_CitySelectTableHeaderView *myTableHeaderView;
@property (nonatomic, strong) UIView *myTableFooterView;

/** 当前定位城市 */
@property (nonatomic, strong) GW_ClubListHome_SelectCityModel *localProvince_Model;
/** 热门 城市 */
@property (nonatomic, strong) NSArray <GW_ClubListHome_SelectCityModel *> *hotProvince_Models;
/** 全部 城市 */
@property (nonatomic, strong) NSArray <GW_ClubListHome_SelectCityModel *> *allProvince_Models;

// 城市 二维数组:
@property (nonatomic, strong) NSMutableArray *section_cityCollationArray;
// 字母 (处理之后的侧边栏的 字母数组,将没有这个拼音的时候,去掉)
@property (nonatomic, strong) NSArray *charArray;

@end

@implementation GW_ClubListHome_CitySelectView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
        
//        [self gainCityDataAndShowCityViewRequest];
    }
    return self;
}

- (void)refreshData {
    [self gainCityDataAndShowCityViewRequest];
}

#pragma mark -- -- 选择地区
- (void)gainCityDataAndShowCityViewRequest {
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = @{
        @"lat":@([GWLocationContext sharedLocationModelInfoContext].locationModel.currlat),
        @"lon":@([GWLocationContext sharedLocationModelInfoContext].locationModel.currlon)
    };
    
    [BRNetworkHepler getWithUrl:@"/golf/court/getProvince" params:params headers:nil success:^(GWHttpBaseResponseModel *responseObject, NSString *message) {
        NSInteger code = responseObject.code;
        if (code == 200) {
            
            NSArray *allProvinceArray = [responseObject.data objectForKey:@"allProvince"];
            NSArray *hotProvinceArray = [responseObject.data objectForKey:@"hotProvince"];
            NSDictionary *localProvinceDic = [responseObject.data objectForKey:@"localProvince"];
            
            // 全部 城市
            NSMutableArray *allProvinceModels = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dic in allProvinceArray) {
                GW_ClubListHome_SelectCityModel *model = [GW_ClubListHome_SelectCityModel modelWithDictionary:dic];
                [allProvinceModels addObject:model];
            }
            self.allProvince_Models = [allProvinceModels copy];
            
            // 热门 城市
            NSMutableArray *hotProvinceModels = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dic in hotProvinceArray) {
                GW_ClubListHome_SelectCityModel *model = [GW_ClubListHome_SelectCityModel modelWithDictionary:dic];
                [hotProvinceModels addObject:model];
            }
            self.hotProvince_Models = [hotProvinceModels copy];
            
            
            // 当前 城市
            self.localProvince_Model = [GW_ClubListHome_SelectCityModel modelWithDictionary:localProvinceDic];
            
            self.myTableHeaderView.localProvince_Model = self.localProvince_Model;
            self.myTableHeaderView.hotProvince_Models = self.hotProvince_Models;
            [self.myTableHeaderView refreshCollectionView];
            
            self.myTableHeaderView.selectHotCityModelBlock = ^(GW_ClubListHome_SelectCityModel * _Nonnull hotCityModel) {
                // 选择的热门城市
                [LCM_AlertViewFactory showToastWithMessage:[NSString stringWithFormat:@"选择的热门城市 是 -- %@,id = %ld", hotCityModel.provinceName, hotCityModel.city_id]];
                
                if (weakSelf.selectCityModelBlock) {
                    weakSelf.selectCityModelBlock(hotCityModel);
                }
            };
            
            [self setupCityCollation];
            
//            [self.tableView reloadData];
        } else {
#ifdef DEBUG
            [LCM_AlertViewFactory showToastWithMessage:responseObject.msg];
#endif
        }
        
    } failure:^(NSError *error, NSString *message) {
        NSLog(@"error ====>>>> %@", error);
        NSLog(@"message ==>> %@", message);
    }];
    
    
}

- (void)setupUI {
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tableView.separatorInset = UIEdgeInsetsMake(0, [UIScreen mainScreen].bounds.size.width/375*20, 0, [UIScreen mainScreen].bounds.size.width/375*20);
    _tableView.separatorColor = RGBA(228, 229, 229, 1);
    _tableView.backgroundColor = RGBA(248, 249, 250, 1);
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator   = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        _tableView.fillerRowHeight = 0;
    }
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    self.tableView.tableHeaderView = self.myTableHeaderView;
    self.tableView.tableFooterView = self.myTableFooterView;
    [self.tableView registerClass:[GW_ClubListHome_CitySelectViewCell class] forCellReuseIdentifier:NSStringFromClass([GW_ClubListHome_CitySelectViewCell class])];
    
}

#pragma mark -- -- 设置 侧边栏:
- (void)setupCityCollation {
    
    /** 全部城市 + 侧边索引栏 */
    NSMutableArray *cityArr = [NSMutableArray arrayWithCapacity:self.allProvince_Models.count];
    
    for (GW_ClubListHome_SelectCityModel *cityModel in self.allProvince_Models) {
        [cityArr addObject:cityModel];
    }
    
    // 1、初始化,并设置如下一行: 这个对象中包含26个大写字母A-Z 和 #
    NSArray *titles = self.cityCollation.sectionTitles;
    
    // 2、定义一个二维数组,数组中的共有27个元素,每个元素又是一个数组,分别对应字母A、B、C、D...#的数据
    NSMutableArray *secionArray = [NSMutableArray arrayWithCapacity:titles.count];
    //向二维数组中添加小数组
    for (int i = 0; i < titles.count; i++) {
        NSMutableArray *subArr = [NSMutableArray array];
        [secionArray addObject:subArr];
    }
    
    for (GW_ClubListHome_SelectCityModel *cityModel in cityArr) {
        // 这个方法会根据@selector中的方法返回的字符串的拼音首字母,找到这个首字母对应的下标index
        NSInteger section = [self.cityCollation sectionForObject:cityModel collationStringSelector:@selector(provinceName)]; // model 中的城市名字 provinceName
        //根据index取出二维数组中的一维数组数组元素
        NSMutableArray *subArr = secionArray[section];
        //将这个对象加入到一维数组数组中  也就是以字母A开头的对象如阿福会被加入到A字母所对应数组,其他字母同理
        [subArr addObject:cityModel];
    }
    
    
    // 3、遍历二维数组,取出每一个一维数组,在对数组中的对象按照字母进行下排序。
    NSMutableArray *section_cityCollationArray = [NSMutableArray arrayWithCapacity:0];
//    for (NSMutableArray *arr in secionArray) {
//
//        NSArray *sortArr = [self.cityCollation sortedArrayFromArray:arr collationStringSelector:@selector(provinceName)]; // model 中的城市名字 provinceName
//
//        [arr removeAllObjects];
//        [arr addObjectsFromArray:sortArr];
//
//        [section_cityCollationArray addObject:arr];
//
//    }
    
    /** 处理:侧边栏的字母 对应的二维数组的小数组,小数组元素个数为0个时,删掉侧边栏的该字母 */
    NSMutableArray *charArr = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < secionArray.count; i++) {
        NSMutableArray *arr = secionArray[i];
        NSArray *sortArr = [self.cityCollation sortedArrayFromArray:arr collationStringSelector:@selector(provinceName)];
        [arr removeAllObjects];
        [arr addObjectsFromArray:sortArr];
        
        if (arr.count > 0) {
            [section_cityCollationArray addObject:arr];
            
            NSString *charStr = titles[i];
            [charArr addObject:charStr];
        }
        
    }
    
    
    
    self.charArray = [charArr copy];
    
    self.section_cityCollationArray = [section_cityCollationArray mutableCopy];
    
    // Appearance
    // 定义tableview右侧section的外观(侧边栏)
    // 文字颜色
    self.tableView.sectionIndexColor = RGBA(9, 9, 9, 1);
    // 背景颜色
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
   // 触摸section区域时候的背景颜色
    self.tableView.sectionIndexTrackingBackgroundColor = [UIColor greenColor];
    self.tableView.sectionIndexMinimumDisplayRowCount = self.charArray.count;
    
    
    
    [self.tableView reloadData];
}

- (UILocalizedIndexedCollation *)cityCollation {
    if (!_cityCollation) {
        _cityCollation = [UILocalizedIndexedCollation currentCollation]; // 初始化UILocalizedIndexedCollation对象
    }
    return _cityCollation;
}


/**返回右侧索引所包含的内容*/
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    NSMutableArray *sections = [self.cityCollation.sectionTitles mutableCopy];
    
    //往索引数组的开始处添加一个放大镜🔍 放大镜是系统定义好的一个常量字符串表示UITableViewIndexSearch 当然除了放大镜外也可以添加其他文字
//    [sections insertObject:UITableViewIndexSearch  atIndex:0];
    
//    NSArray *arr = @[@"1",@"2",@"3",@"4",];
//    return arr;
    
    
    // 可以自定义,将二维数组中,小数组有值时,对应的拼音返回,小数组为的元素数量为0的,对应拼音不返回
    
    return self.charArray;
    
//    return sections;
    
}

//返回每个section的title
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([[self.section_cityCollationArray objectAtIndex:section] count] > 0) {
//        return [[self.cityCollation sectionTitles] objectAtIndex:section];
        
        return [self.charArray objectAtIndex:section];
    } else {
        return nil;
    }
    
//    return self.cityCollation.sectionTitles;
}

//点击右侧索引后跳转到的section
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    
    NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index];
       
    if (![self.section_cityCollationArray[index] count]) {
        return 0;
        
    }else{
        
        [tableView scrollToRowAtIndexPath:selectIndexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        
        return index;
    }
}

// 比如修改索引文本的字体大小
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    for (UIView *view in [tableView subviews]) {
        if ([view isKindOfClass:[NSClassFromString(@"UITableViewIndex") class]]) {
           
            /** 索引(UITableViewIndex)其他属性(非公开的):
             
             titles      //不知名属性
             font       //字体大小
             drawingInsets  //拓展范围
             indexColor  //字体颜色
             indexBackgroundColor //背景颜色
             indexTrackingBackgroundColor
             selectedSection  //选中之类
             selectedSectionTitle  //猜测试 indexTitle
             pastTop
             pastBottom
             
             比如:UITableViewIndex的内部属性是有限的,如果我们只是简单的设置一下字体、颜色等,可以通过UITableViewIndex的内部属性进行设置,简单方便。
             */
            
            // 设置字体大小
            [view setValue:[UIFont systemFontOfSize:[UIScreen mainScreen].bounds.size.width/375*12 weight:UIFontWeightRegular] forKey:@"_font"];
           //设置view的大小
//            view.bounds = CGRectMake(0, 0, 50, 50);
            //单单设置其中一个是无效的
            
            
        }
    }
}


#pragma mark -- <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.section_cityCollationArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.section_cityCollationArray objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [UIScreen mainScreen].bounds.size.width/375* 46;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GW_ClubListHome_CitySelectViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GW_ClubListHome_CitySelectViewCell class]) forIndexPath:indexPath];
    if ([[self.section_cityCollationArray objectAtIndex:indexPath.section] count] > 0) {
        GW_ClubListHome_SelectCityModel *cityModel = [self.section_cityCollationArray[indexPath.section] objectAtIndex:indexPath.row];
        
        cell.cityModel = cityModel;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    GW_ClubListHome_SelectCityModel *cityModel = [self.section_cityCollationArray[indexPath.section] objectAtIndex:indexPath.row];
    [LCM_AlertViewFactory showToastWithMessage:[NSString stringWithFormat:@"名字 == %@, id = %ld", cityModel.provinceName, cityModel.city_id]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    NSLog(@"😆😆 section = %ld", [[self.section_cityCollationArray objectAtIndex:section] count]);
    
    if ([[self.section_cityCollationArray objectAtIndex:section] count] > 0) {
        return [UIScreen mainScreen].bounds.size.width/375* 30;
    } else {
        return 0;
    }
    
}

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

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
////    UIView *headerView = [UIView new];
////
////    return headerView;
//    return nil;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    return nil;
//}


#pragma mark -- 懒加载
- (GW_ClubListHome_CitySelectTableHeaderView *)myTableHeaderView {
    if (!_myTableHeaderView) {
        _myTableHeaderView = [[GW_ClubListHome_CitySelectTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width/375* 171)];
    }
    return _myTableHeaderView;
}

- (UIView *)myTableFooterView {
    if (!_myTableFooterView) {
        _myTableFooterView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width/375* 5)];
        self.myTableFooterView.backgroundColor = RGBA(248, 249, 250, 1);
    }
    return _myTableFooterView;
}

相关文章

网友评论

      本文标题:iOS~ tableview侧边索引栏(如:通讯录右侧拼音栏):

      本文链接:https://www.haomeiwen.com/subject/ghwsprtx.html