ios - 在 iOS 中点击时如何更改 UITableView 标题背景颜色

标签 ios objective-c iphone uitableview uitableviewsectionheader

我想在每个 View 中点击时更改点击的 UITableView 标题。我写了以下代码,但它根本不起作用。请帮助解决该问题。

- (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;
}

最佳答案

你可以使用这个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;
    }
}

关于ios - 在 iOS 中点击时如何更改 UITableView 标题背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35545627/

相关文章:

ios - 从 mapView.annotations 访问 MKAnnotationView

iphone - 我应该将 UIBarButtonItem 设置为多宽才能制作方形按钮?

iphone - 使用 Test Flight App 对随机数进行 Beta 测试有什么危险?

带有空字符串的 iOS UILabel 零高度

ios - 检查两个日期是否等于分钟精度

ios - Objective-C 自动释放内存管理

ios - 未声明的标识符不会消失

ios - 我改变观点的方式有问题吗?

iphone - 如何使用swift在游戏中心报告高分

ios - Segues 与 UIViewControllerAnimatedTransitioning