【问题标题】:How to change UITableViewHeader background color when tapped in iOS在iOS中点击时如何更改UITableView Header背景颜色
【发布时间】:2016-02-22 04:02:36
【问题描述】:

我想在每个视图中点击时更改点击的 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;
}

【问题讨论】:

  • 您可以使用按钮来代替标签并移除点击手势。
  • 如果你只想改变背景颜色,那么按钮是更可取的,否则对于视图的巨大变化你可以去点击手势。但我怀疑点击手势只能在标题上工作,它可以在整个 tableview 上工作,在这种情况下不会调用 didSelect 委托函数。
  • 我只想更改标题视图。

标签: ios objective-c iphone uitableview uitableviewsectionheader


【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多