【问题标题】:Changing color of section header in UITableview在 UITableview 中更改节标题的颜色
【发布时间】:2011-01-24 07:07:22
【问题描述】:

我有一个非常简单的问题(我希望如此)。如何将 UITableview 中的部分标题颜色从默认的蓝色更改为黑色透明? 提前致谢。

【问题讨论】:

标签: iphone objective-c uitableview sectionheader


【解决方案1】:

这是一个老问题,但我认为答案需要更新。

此方法不涉及定义您自己的自定义视图。
在 iOS 6 及更高版本中,您可以通过定义

轻松更改背景颜色和文本颜色
- (void)tableView:(UITableView *)tableView
        willDisplayHeaderView:(UIView *)view
        forSection:(NSInteger)section
委托方法。

例如:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { // 背景颜色 view.tintColor = [UIColor blackColor]; // 文字颜色 UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; [header.textLabel setTextColor:[UIColor whiteColor]]; //另一种设置背景颜色的方法 // 注意:不保留原标题的渐变效果 // header.contentView.backgroundColor = [UIColor blackColor]; }

摘自我的帖子: https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/

【讨论】:

    【解决方案2】:

    你需要在 UITableViewDelegate 协议中实现这个方法:

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

    这是documentation的链接

    ...并做这样的事情(以您自己的颜色替换):

    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 22)] autorelease];
    [sectionView setBackgroundColor:[UIColor blackColor]];
    return sectionView;
    

    您还可以使用部分整数来交替颜色或类似的东西。我认为这些部分的默认高度是 22,但您可以随意设置。这就是你的问题的意思吗?希望这会有所帮助。

    【讨论】:

    • 谢谢,我认为在 IB 中会有某种触发器来切换到黑色。但无论如何,谢谢。
    • 但是请缓存这些视图。 UIKit 中存在一个错误,导致在滚动 tableView 时请求标题视图,因此滚动时每个像素偏移都会调用此方法。 22px 确实是默认高度。
    • 嗨,我知道当滚动发生时这个方法会被调用......我们如何缓存它以保存创建不必要的视图等......?如果您可以发表评论或更新您的帖子,那将非常有帮助。谢谢
    【解决方案3】:
    - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
       {
         UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,tableView.bounds.size.width, 30)];
         if (section == 0)
         [headerView setBackgroundColor:[UIColor redColor]];
         else 
         [headerView setBackgroundColor:[UIColor clearColor]];
         return headerView;
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-18
      • 2010-10-23
      • 2011-03-18
      • 2020-08-12
      • 2012-09-10
      • 2013-01-03
      • 2015-07-26
      • 1970-01-01
      相关资源
      最近更新 更多