美文网首页ios新知识iOS点滴将来跳槽用
改变UITableView的headerView、footerV

改变UITableView的headerView、footerV

作者: 戴仓薯 | 来源:发表于2015-03-30 22:57 被阅读8011次

    问题

    改变UITableView的header、footer背景颜色,这是个很常见的问题。之前知道的一般做法是,通过实现tableView: viewForHeaderInSection:返回一个自定义的View,里面什么都不填,只设背景颜色。但是今天发现一个更简洁的做法。

    更简洁的方法

    对于iOS 6及以后的系统,实现这个新的delegate函数即可:

    - (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
        view.tintColor = [UIColor clearColor];
    }
    

    还可以改变文字的颜色:

    - (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
    {
        UITableViewHeaderFooterView *footer = (UITableViewHeaderFooterView *)view;
        [footer.textLabel setTextColor:[UIColor whiteColor]];
    }
    

    错误的尝试

    写这篇文章的目的,主要是想记录两种错误的尝试。
    当看到这个Delegate函数时,第一反应是想当然地这样做:

    错误尝试1

    - (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
        view.backgroundColor = [UIColor clearColor];
    }
    

    这样做是无效的,无论对什么颜色都无效。

    错误尝试2

    - (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section
    {
        UITableViewHeaderFooterView *footer = (UITableViewHeaderFooterView *)view;
        footer.contentView.backgroundColor = [UIColor redColor];
    }
    

    这样做设成不透明的颜色就没问题。但设成clearColor,看到的还是灰色。


    本文参考

    UITableView - change section header color

    相关文章

      网友评论

      • 疯人院院长:headerView.contentView.backgroundColor =...;
      • char_hu:写得好,哈哈,我是刚遇到这个问题,才找到你这里的解决方案,很管用。赞!
        戴仓薯:@5183ae9429f4 哈哈, 有可能,这篇文章已经太老了~~ 后面我也米再用过 = = 其实就返回一个 custom 的 view 最合适
        char_hu:@5183ae9429f4 这个方案,还是有点问题,一旦tableView滚动后,还是会出来那个颜色。比较好的方案,网上有另一位网友提供的:http://blog.csdn.net/liwenjie0912/article/details/41806243
        不过这个方案,我个人感觉有点啰嗦。
        我解决的方案,在他的基础上就一句话:
        headerView.backgroundView = [UIView new];
      • Solin_solin:一样没效果 :unamused:
        Solin_solin:@爱情壁 http://my.oschina.net/u/811205/blog/362229 要注意这个坑
      • 一帆_iOS程序员:请问,我这边改完,tableview的headview的颜色怎么没有改变呢?急等
        方同学哈:tableView设置为plain
        Solin_solin:@一帆_iOS程序员 http://my.oschina.net/u/811205/blog/362229
        戴仓薯:@一帆_iOS程序员 不好意思哈,这是很久以前的文章,我后来一直没注意评论。如果还需要帮助的话,可以把代码贴出来看看。

      本文标题:改变UITableView的headerView、footerV

      本文链接:https://www.haomeiwen.com/subject/uzqoxttx.html