UITableView cell的展开与收起(伴随指示箭头)

1.第一步

//创建数据源并创建一个记录是否展开的数据源
@property (nonatomic, strong)NSMutableArray *dataArray;//数据
@property (nonatomic, strong)NSMutableArray<NSNumber *> *isExpland;//是否展开

2.第二步

- (void)viewDidLoad {
    [super viewDidLoad];
 if (!self.dataArray) {
        self.dataArray = [NSMutableArray array];
    }
    if (!self.isExpland) {
        self.isExpland = [NSMutableArray array];
    }
    titleArray1 = @[@"服务人次",@"充值业绩",@"铺垫目标",@"消费业绩"];
    titleArray2 = @[@"调理备忘",@"回访顾客",@"预约提醒"];

    //用一个二维数组来模拟数据。
    self.dataArray = [NSArray arrayWithObjects:titleArray1,titleArray2,nil].mutableCopy;

    //用0代表收起,非0(不一定是1)代表展开,默认都是收起的
    for (int i = 0; i < self.dataArray.count; i++) {
        [self.isExpland addObject:@1];
    }
}

3.第三步(很重要的一步)

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{  
//利用数据源展示row的个数, 并根据是否展开返回具体个数,展开返回正常个数,关闭则为0
    NSArray *array = self.dataArray[section];
    if ([self.isExpland[section] boolValue]) {
        return array.count;
    }
    else {
        return 0; 
    }
}

4.第四步(headerView的处理)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    headerView.backgroundColor = [UIColor whiteColor];

   //展开的小尖头V
   UIImageView  *arrowImageView = [[UIImageView alloc] init];
    arrowImageView.tag = 600+section;
    UIImage *img = [UIImage imageNamed:@"h_sum_arrow_blue_15x9"];
    [headerView addSubview:arrowImageView];

    //根据是否展开显示尖头的方向(向下或向上)
    if (![self.isExpland[section] boolValue]){
   //image的翻转
        img = [UIImage imageWithCGImage:img.CGImage scale:1 orientation:UIImageOrientationDown];
    }
    arrowImageView.image = img;

 UIButton *headerBtn = [[UIButton alloc] init];
    headerBtn.tag = 666+section;//添加标记
    [headerBtn addTarget:self action:@selector(headerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:headerBtn];

    arrowImageView.sd_layout
    .rightEqualToView(headerView).offset(-15)
    .centerYEqualToView(headerView)
    .widthIs(15)
    .heightIs(9);

 headerBtn.sd_layout
    .leftEqualToView(headerView)
    .topSpaceToView(headerView,0)
    .widthRatioToView(headerView,1)
    .heightRatioToView(headerView,1);

    return headerView;
}

5.第五步(点击处理)

- (void)headerButtonAction:(UIButton *)button
{
    UIImageView *imageView = (UIImageView *)[self.view viewWithTag:600+button.tag - 666];
    imageView.transform = CGAffineTransformMakeRotation(M_PI);

    NSInteger section = button.tag - 666;
    self.isExpland[section] = [self.isExpland[section] isEqual:@0]?@1:@0;
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:section];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}
IT文库 » UITableView cell的展开与收起(伴随指示箭头)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址