刷新tableView 保持头部视图 不变

1. 声明全局变量

  UIView *headView; 表头部View

    UIButton *financeBtn; //金融头条Btn

    UIButton *companyNewsBtn;//公司新闻Btn

2.在viewDidLoad里面 

- (void)viewDidLoad {

    [super viewDidLoad];

    float screenWidth = kUIScreenWidth -70;

    financeBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    [financeBtn setTitle:@"金融头条" forState:UIControlStateNormal];

    [financeBtn.titleLabel setFont:[UIFont fontWithName:kPingFang_Medium size:14]];

    [financeBtn setFrame:CGRectMake(screenWidth/4-40, 12, 80, 25)];

    [financeBtn setTitleColor:[CommonFunctions colorWithHex:0x11a1b4] forState:UIControlStateNormal];

    [financeBtn setTag:222];

    [financeBtn addTarget:self action:@selector(companyNewsBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    companyNewsBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    [companyNewsBtn setTitle:@"公司新闻" forState:UIControlStateNormal];

    [companyNewsBtn.titleLabel setFont:[UIFont fontWithName:kPingFang_Medium size:14]];

    [companyNewsBtn setFrame:CGRectMake((screenWidth/2)+(screenWidth/4-40), 12, 80, 25)];

    [companyNewsBtn setTitleColor:[CommonFunctions colorWithHex:0x999999] forState:UIControlStateNormal];

    [companyNewsBtn addTarget:self action:@selector(companyNewsBtnClick:) forControlEvents:UIControlEventTouchUpInside];

    [companyNewsBtn setTag:333];

}

3.  区头设置    在方法里面判断不让按钮循环创建

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

     headView = [[UIView alloc] initWithFrame:CGRectMake(0, -1, kUIScreenWidth, 69)];

    headView.backgroundColor = [UIColor whiteColor];

   if(section == 0) {

        UIButton *mergeBtn = (UIButton *)[self.view viewWithTag:222];

        if (mergeBtn == nil) {

            [headView addSubview:financeBtn];

            [headView addSubview:companyNewsBtn];

        }

    }

return headView;

4. 实现按钮的点击方法就OK了

#pragma mark  金融头条和公司新闻 Btn

- (void)companyNewsBtnClick:(UIButton *)sender {

   float screenWidth = kUIScreenWidth -70;

    UIButton *changeBtn = (UIButton *)[self.view viewWithTag:sender.tag];

    [changeBtn setTitleColor:[CommonFunctions colorWithHex:0x11a1b4] forState:UIControlStateNormal];

    if (sender.tag == 222) {

        NSLog(@"金融头条");

        picImg.frame = CGRectMake(screenWidth/4-40, -1, 80, 4);

        [companyNewsBtn setTitleColor:[CommonFunctions colorWithHex:0x999999] forState:UIControlStateNormal];

    }else if (sender.tag == 333) {

        NSLog(@"公司新闻");

        picImg.frame = CGRectMake((screenWidth/2)+(screenWidth/4-40), -1, 80, 4);

        [financeBtn setTitleColor:[CommonFunctions colorWithHex:0x999999] forState:UIControlStateNormal];

    }

}

 

效果图 如下:

原文地址:https://www.cnblogs.com/Lovexiaohuzi/p/6931792.html