1

我想在每个视图中点击时更改点击UITableViewHeader。我写了下面的代码,但它根本不起作用。请帮助如何解决这个问题。如何在iOS中点击时更改UITableViewHeader背景颜色

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

    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 25)]; 
    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, tableView.frame.size.width, 25)]; 
    [label setFont:CHECKOUT_HEADER_FONT]; 
    label.textColor = GLOBAL_PRIMARY_COLOR; 
    label.textAlignment = NSTextAlignmentLeft; 
    [label setText:CategoryName]; 
    label.backgroundColor = GLOBAL_BACKGROUND; 
    [view setBackgroundColor: GLOBAL_BACKGROUND]; 
    [view addSubview:label]; 

    view.tag = section; 
    UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)]; 
    [view addGestureRecognizer:headerTapped]; 

    return view; 
} 


- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag]; 

    // DOES NOT WORK 
    UIView *header = [_productTableView headerViewForSection:indexPath.section]; 
    header.backgroundColor = GLOBAL_PRIMARY_COLOR; 
} 
+0

您可以使用一个按钮,而不是标签,并删除轻敲手势。 –

+0

为什么要使用按钮? – ppshein

+0

如果你只想改变背景颜色,那么按钮是最好的,否则在视图的巨大变化,你可以去点击手势。但我怀疑,轻拍手势只能在标题上工作,它可以作为一个整体在tableview上工作,在这种情况下,didSelect委托函数将不会被调用。 –

回答

1

您可以使用此viewForHeaderInSection

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UIView *tempView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 25)]; 
    tempView.backgroundColor=[UIColor blueColor]; 

    tempView.tag = section; 
    UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)]; 
    [tempView addGestureRecognizer:headerTapped]; 

    return tempView; 
} 
- (IBAction)sectionHeaderTapped:(UITapGestureRecognizer *)recognizer 
{ 
    switch (recognizer.view.tag) { 
     case 0: 
      recognizer.view.backgroundColor = [UIColor redColor]; 
      break; 

     default: 
      break; 
    } 
} 
相关问题