Expand/collapse section in UITableView in iOS

前端 未结 17 927
野的像风
野的像风 2020-11-22 08:49

Could somebody tell me the way to perform UITableView expandable/collapsible animations in sections of UITableView as below?

<

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:46

    // -------------------------------------------------------------------------------
    //  tableView:viewForHeaderInSection:
    // -------------------------------------------------------------------------------
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
        UIView *mView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        [mView setBackgroundColor:[UIColor greenColor]];
    
        UIImageView *logoView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 20, 20)];
        [logoView setImage:[UIImage imageNamed:@"carat.png"]];
        [mView addSubview:logoView];
    
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        [bt setFrame:CGRectMake(0, 0, 150, 30)];
        [bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [bt setTag:section];
        [bt.titleLabel setFont:[UIFont systemFontOfSize:20]];
        [bt.titleLabel setTextAlignment:NSTextAlignmentCenter];
        [bt.titleLabel setTextColor:[UIColor blackColor]];
        [bt setTitle: @"More Info" forState: UIControlStateNormal];
        [bt addTarget:self action:@selector(addCell:) forControlEvents:UIControlEventTouchUpInside];
        [mView addSubview:bt];
        return mView;
    
    }
    
    #pragma mark - Suppose you want to hide/show section 2... then
    #pragma mark  add or remove the section on toggle the section header for more info
    
    - (void)addCell:(UIButton *)bt{
    
        // If section of more information
        if(bt.tag == 2) {
    
            // Initially more info is close, if more info is open
            if(ifOpen) {
                DLog(@"close More info");
    
                // Set height of section
                heightOfSection = 0.0f;
    
                // Reset the parameter that more info is closed now
                ifOpen = NO;
            }else {
                // Set height of section
                heightOfSection = 45.0f;
                // Reset the parameter that more info is closed now
                DLog(@"open more info again");
                ifOpen = YES;
            }
            //[self.tableView reloadData];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
        }
    
    }// end addCell
    #pragma mark -
    #pragma mark  What will be the height of the section, Make it dynamic
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        if (indexPath.section == 2) {
            return heightOfSection;
        }else {
            return 45.0f;
        }
    

    // vKj

提交回复
热议问题