Adding UIButton to UITableView section header

前端 未结 7 1132
一个人的身影
一个人的身影 2021-02-01 20:20

I have a UITableView with 1 section and for the section header, I would like to keep everything about the header the same but simply add a button on the right side.

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 21:09

    From iOS 6, you can also implement

    - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
    

    in your UITableViewDelegate. For example:

    - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
        if (section == 0) {
            if ([view.subviews.lastObject isKindOfClass:[UIButton class]]) {
                return;
            }
            UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake(view.frame.size.width - 160.0, 0, 160.0, view.frame.size.height); // x,y,width,height
            [button setTitle:@"My Button" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(sectionHeaderButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
        }
    }
    

提交回复
热议问题