美文网首页
iOS UITableView分组展开/关闭

iOS UITableView分组展开/关闭

作者: 浅宇落 | 来源:发表于2019-09-29 08:22 被阅读0次

    效果图

    效果图.gif

    1. CommonProblemsModel模型

    CommonProblemsModel.h

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface CommonProblemsModel : NSObject
    /** 标题 */
    @property (nonatomic, copy) NSString *headerTitle;
    /** 回答内容 */
    @property (nonatomic, strong) NSMutableArray *answers;
    
    
    /************* 额外属性 ***************/
    
    /** 分组是否展开 YES:展开 NO:关闭 */
    @property (nonatomic, assign) BOOL isAn;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    CommonProblemsModel .m

    #import "CommonProblemsModel.h"
    #import "MJExtension.h"
    
    @implementation CommonProblemsModel
    MJCodingImplementation
    
    + (NSDictionary *)mj_objectClassInArray {
        return @{@"answers" : @"CommonProblemsAnswerModel"};
    }
    @end
    

    2. CommonProblemsAnswerModel模型

    CommonProblemsAnswerModel.h

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface CommonProblemsAnswerModel : NSObject
    /** 标题 */
    @property (nonatomic, copy) NSString *content;
    
    
    /************* 额外属性 ***************/
    
    /** cell高度 */
    @property (nonatomic, assign, readonly) CGFloat cellH;
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    CommonProblemsAnswerModel.m

    #import "CommonProblemsAnswerModel.h"
    #import "NSString+XMGExtension.h"
    #import "MJExtension.h"
    
    @implementation CommonProblemsAnswerModel
    MJCodingImplementation
    
    
    /**
     *  当字典转模型完毕时调用
     */
    - (void)mj_keyValuesDidFinishConvertingToObject {
        
       CGFloat contentH =  [self.content textHeightWithFont:[UIFont fontWithName:@"PingFangSC-Regular" size:15] textWidth:[UIScreen mainScreen].bounds.size.width - 50 - 14];
        
        /** cell高度 */
        _cellH = 15 + 15 + 28 + 20 + contentH;
    }
    @end
    

    3.分区头部(CommonProblemsSectionHeaderView)

    CommonProblemsSectionHeaderView.h

    #import <UIKit/UIKit.h>
    @class CommonProblemsModel;
    @class CommonProblemsSectionHeaderView;
    
    @protocol CommonProblemsSectionHeaderViewDelegate <NSObject>
    
    /**
     展开/关闭 代理
     */
    - (void)commonProblemsSectionHeader:(CommonProblemsSectionHeaderView *_Nullable)commonProblemsSectionHeader isAn:(BOOL)isAn indexPath:(NSIndexPath *_Nullable)indexPath;
    
    @end
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface CommonProblemsSectionHeaderView : UITableViewHeaderFooterView
    /**
     刷新UI
    
     @param model 模型
     @param indexPath 位置
     */
    - (void)refreshUIModel:(CommonProblemsModel *)model indexPath:(NSIndexPath *)indexPath;
    
    /** 代理 */
    @property (weak, nonatomic) id<CommonProblemsSectionHeaderViewDelegate> delegate;
    
    
    @end
    
    NS_ASSUME_NONNULL_END
    

    CommonProblemsSectionHeaderView.m

    #import "CommonProblemsSectionHeaderView.h"
    #import "Masonry.h"
    #import "CommonProblemsModel.h"
    #import "UIColor+Random.h"
    
    @interface CommonProblemsSectionHeaderView ()
    /** 标题 */
    @property (nonatomic, strong) UILabel *titleLabel;
    /** 方向按钮 */
    @property (nonatomic, strong) UIButton *directionBtn;
    /** 分割线上 */
    @property (nonatomic, strong) UIView *lineOnView;
    /** 分割线下 */
    @property (nonatomic, strong) UIView *lineUnderView;
    
    /** 位置 */
    @property (nonatomic, strong) NSIndexPath *indexPath;
    /** 模型 */
    @property (nonatomic, strong) CommonProblemsModel *model;
    @end
    
    @implementation CommonProblemsSectionHeaderView
    
    - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
        if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
            self.contentView.backgroundColor = [UIColor whiteColor];
            // 创建UI
            [self createUI];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickTapAction)];
            [self.contentView addGestureRecognizer:tap];
        }
        return self;
    }
    
    #pragma mark - 创建UI
    - (void)createUI {
        /** 标题 */
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.textColor = [UIColor rgbColorWithRed:26 green:26 blue:26 opacity:1];
        self.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        [self.contentView addSubview:self.titleLabel];
        
        /** 方向按钮 */
        self.directionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.directionBtn.userInteractionEnabled = NO;
        [self.directionBtn setBackgroundImage:[UIImage imageNamed:@"向下"] forState:UIControlStateNormal];
        [self.directionBtn setBackgroundImage:[UIImage imageNamed:@"向上"] forState:UIControlStateSelected];
        [self.contentView addSubview:self.directionBtn];
        
        /** 分割线上 */
        self.lineOnView = [[UIView alloc] init];
        self.lineOnView.backgroundColor = [UIColor rgbColorWithRed:245 green:245 blue:245 opacity:1];
        [self.contentView addSubview:self.lineOnView];
        
        /** 分割线下 */
        self.lineUnderView = [[UIView alloc] init];
        self.lineUnderView.backgroundColor = [UIColor rgbColorWithRed:245 green:245 blue:245 opacity:1];
        [self.contentView addSubview:self.lineUnderView];
    }
    
    #pragma mark - 刷新UI
    - (void)refreshUIModel:(CommonProblemsModel *)model indexPath:(NSIndexPath *)indexPath {
        /** 标题 */
        self.titleLabel.text = model.headerTitle;
        
        /** 方向按钮 */
        self.directionBtn.selected = model.isAn;
        
        // 赋值
        self.indexPath = indexPath;
        self.model = model;
    }
    
    #pragma mark - 手势 点击事件
    - (void)clickTapAction {
        // 执行代理
        if ([self.delegate respondsToSelector:@selector(commonProblemsSectionHeader:isAn:indexPath:)]) {
            self.model.isAn = !self.model.isAn;
            self.directionBtn.selected = self.model.isAn;
            [self.delegate commonProblemsSectionHeader:self isAn:self.model.isAn indexPath:self.indexPath];
        }
    }
    
    #pragma mark - 布局
    - (void)layoutSubviews {
        [super layoutSubviews];
        
        /** 标题 */
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.equalTo(self.contentView);
        }];
        
        /** 方向按钮 */
        [self.directionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.contentView).offset(-12);
            make.centerY.equalTo(self.contentView);
        }];
        
        /** 分割线上 */
        [self.lineOnView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(0);
            make.right.equalTo(self.contentView);
            make.height.mas_equalTo(1);
        }];
        
        /** 分割线下 */
        [self.lineUnderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.equalTo(self.contentView);
            make.height.mas_equalTo(1);
            make.bottom.equalTo(self.contentView);
        }];
    }
    
    @end
    
    

    4.cell(CommonProblemsCell)

    CommonProblemsCell.h

    #import <UIKit/UIKit.h>
    @class CommonProblemsAnswerModel;
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface CommonProblemsCell : UITableViewCell
    /** 模型 */
    @property (nonatomic, strong) CommonProblemsAnswerModel *model;
    @end
    
    NS_ASSUME_NONNULL_END
    

    CommonProblemsCell.m

    #import "CommonProblemsCell.h"
    #import "CommonProblemsAnswerModel.h"
    #import "Masonry.h"
    #import "UIColor+Random.h"
    
    @interface CommonProblemsCell ()
    /** 背景图 */
    @property (nonatomic, strong) UIImageView *bgImg;
    /** 回答图片 */
    @property (nonatomic, strong) UIImageView *answerImg;
    /** 内容 */
    @property (nonatomic, strong) UILabel *contentLabel;
    @end
    
    @implementation CommonProblemsCell
    
    - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
        if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
            self.selectionStyle = UITableViewCellSelectionStyleNone;
            // 创建UI
            [self createUI];
        }
        return self;
    }
    
    #pragma mark - 创建UI
    - (void)createUI {
        /** 背景图 */
        self.bgImg = [[UIImageView alloc] init];
        self.bgImg.image = [UIImage imageNamed:@"常见问题bg"];
        [self.contentView addSubview:self.bgImg];
        
        /** 回答图片 */
        self.answerImg = [[UIImageView alloc] init];
        self.answerImg.backgroundColor = [UIColor redColor];
        //self.bgImg.image = [UIImage imageNamed:@"常见问题bg"];
        [self.bgImg addSubview:self.answerImg];
        
        /** 内容 */
        self.contentLabel = [[UILabel alloc] init];
        self.contentLabel.numberOfLines = 0;
        self.contentLabel.textColor = [UIColor rgbColorWithRed:26 green:26 blue:26 opacity:1];
        self.contentLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        [self.bgImg addSubview:self.contentLabel];
        
    }
    
    #pragma mark - 模型setter方法
    - (void)setModel:(CommonProblemsAnswerModel *)model {
        _model = model;
        /** 内容 */
        self.contentLabel.text = model.content;
    }
    
    #pragma mark - 布局
    - (void)layoutSubviews {
        [super layoutSubviews];
        
        /** 背景图 */
        [self.bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(12);
            make.right.equalTo(self.contentView).offset(-8);
            make.bottom.equalTo(self.contentView).offset(-15);
        }];
        
        /** 回答图片 */
        [self.answerImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(20, 20));
            make.left.mas_equalTo(12);
            make.top.mas_equalTo(30);
        }];
        
        /** 内容 */
        [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.answerImg.mas_right).offset(6);
            make.top.mas_equalTo(28);
            make.right.equalTo(self.bgImg).offset(-6);
            make.bottom.equalTo(self.bgImg).offset(-20);
        }];
    }
    @end
    
    

    5.使用

    #import "DesVC.h"
    #import "CommonProblemsModel.h"
    #import "CommonProblemsSectionHeaderView.h"
    #import "CommonProblemsAnswerModel.h"
    #import "CommonProblemsCell.h"
    #import "ArchiveTool.h"
    
    @interface DesVC ()<UITableViewDelegate, UITableViewDataSource, CommonProblemsSectionHeaderViewDelegate>
    /** tableView */
    @property (nonatomic, strong) UITableView *tableView;
    /** 数据源 */
    @property (nonatomic, strong) NSMutableArray<CommonProblemsModel *> *dataSoucre;
    @end
    
    static NSString * const cellId = @"DesVCellId";
    static NSString * const headerId = @"DesVCHeaderId";
    
    @implementation DesVC
    - (NSMutableArray<CommonProblemsModel *> *)dataSoucre {
        if (!_dataSoucre) {
            self.dataSoucre = [NSMutableArray array];
            
            NSArray *array = @[
                               @{
                                   @"headerTitle" : @"我能开设多个账户吗?",
                                   @"answers" : @[
                                           @{@"content" : @"平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户"
                                             },
                                           @{@"content" : @"平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户, 平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户, 平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户"
                                             },
                                           @{@"content" : @"平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户"
                                             }
                                           ]
                                   },
                               @{
                                   @"headerTitle" : @"我能开设多个账户吗?",
                                   @"answers" : @[
                                           @{@"content" : @"平台内目前经支持一个身份证开设一个交易账户,一个手机号可绑定一个账户"}
                                           ]
                                   }
                               ];
            
            _dataSoucre = [CommonProblemsModel mj_objectArrayWithKeyValuesArray:array];
            CommonProblemsModel *model = _dataSoucre.firstObject;
            model.isAn = YES;
            
            
            
        }
        return _dataSoucre;
    }
    - (UITableView *)tableView {
        if (!_tableView) {
            CGFloat tableViewTop = 20;
            CGRect frame = CGRectMake(0, tableViewTop, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - tableViewTop);
            self.tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
            _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            _tableView.showsVerticalScrollIndicator = NO;
            _tableView.showsHorizontalScrollIndicator = NO;
            _tableView.dataSource = self;
            _tableView.delegate = self;
            _tableView.sectionHeaderHeight = 53;
            
            [_tableView registerClass:[CommonProblemsSectionHeaderView class] forHeaderFooterViewReuseIdentifier:headerId];
            [_tableView registerClass:[CommonProblemsCell class] forCellReuseIdentifier:cellId];
        }
        
        return _tableView;
    }
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // 添加tableView
        [self.view addSubview:self.tableView];
        
    }
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return self.dataSoucre.count;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        CommonProblemsModel *model = self.dataSoucre[section];
        if (model.isAn) { // 展开
            return self.dataSoucre[section].answers.count;
        }else {
            return 0;
        }
    }
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        CommonProblemsAnswerModel *model = self.dataSoucre[indexPath.section].answers[indexPath.row];
        return model.cellH;
    }
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        CommonProblemsSectionHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
        [headerView refreshUIModel:self.dataSoucre[section] indexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
        headerView.delegate = self;
        return headerView;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        CommonProblemsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
        cell.model = self.dataSoucre[indexPath.section].answers[indexPath.row];
        return cell;
    }
    
    #pragma mark - CommonProblemsSectionHeaderViewDelegate 代理
    - (void)commonProblemsSectionHeader:(CommonProblemsSectionHeaderView *)commonProblemsSectionHeader isAn:(BOOL)isAn indexPath:(NSIndexPath * _Nullable)indexPath {
        // isAn YES:展开   NO:关闭
      
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:indexPath.section];
        // 刷新
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        
    }
    
    @end
    

    ArchiveTool类链接

    相关文章

      网友评论

          本文标题:iOS UITableView分组展开/关闭

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