zoukankan      html  css  js  c++  java
  • UITableView中关于viewForHeaderInSection的一点小坑

    新手入门,在保持兴趣的前提下,最直接的办法就是照着例子手动敲一遍代码,然后将示例跑起来,这样能最直观的看到效果。

    但是,一般的面向初学者的教程或实例,技术面都相对于浅显,实现的效果也比较Low,就像开发商刚盖出的房子一样,也叫房子,但那是毛坯房。相对于有其他语言开发经验或项目经验的初学者(Ps:例如我~)来说,往往会以点带面,会主动去挖掘与教程相关的“姿势点”,想尽办法用已掌握的新技能去将这些实例完善、扩展,想一次就做出精装修的房子。又因为对于一门刚接触的新语言,了解的不够深入,所以也会难免陷入一个个小坑中。

     

    这两天做的实例是编码实现UITableView,还是老样子,不拖控件、不使用Auto Layout布局,要求兼容苹果不同分辨率的三种设备,暂不考虑iPad。

     

    功能很简单,很容易就搞出来了。但是表头很丑,看着很不爽,寻思着是不是给它弄好看一点。

    // 普通设置表头
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
        return @"婴幼儿奶粉品牌列表(默认表头)";
    }

    如下图:

     

    我想要做的是将表头弄漂亮一点,增加一点自定义的元素,比如说加个小icon,加个背景色什么的。

    // 自定义表头
    - (UIView*) tableView:(UITableView *)_tableView viewForHeaderInSection:(NSInteger)section {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width, 50)];
        // left icon
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];
        icon.image = [UIImage imageNamed:@"250x250"];// right text
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, _tableView.frame.size.width-50, 50)];
        label.textColor = [UIColor orangeColor];
        label.text = @"婴幼儿奶粉品牌列表(自定义表头)";
        label.textAlignment = NSTextAlignmentCenter;// 消息方式设置背景色(UIColor最后要转成CGColor类型)
        [headerView.layer setBackgroundColor:[UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1].CGColor];
        // 属性方式设置背景色
        //headerView.backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1];
    
        [headerView addSubview:icon];
        
        [headerView addSubview:label];
        
        return headerView;
    }

    原以为到这里,差不多就实现我想的效果:表头左边有个小icon,右边是文字描述。可偏偏就是没出来我想要的效果,不知道是什么问题。在自定义表头的方法里面打日志,发现程序根本就没进去。。。

    新手嘛,各种google, 找了好多资料后最后在stackoverflow.com上找到一个类似的问题,去看了官方文档才明白是怎么回事。

    知道什么问题就好办了,老老实实去实现tableView:heightForHeaderInSection呗

    // 设置表头的高度。如果使用自定义表头,该方法必须要实现,否则自定义表头无法执行,也不会报错
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
    {
        return 50;
    }

    这下好了,我要的效果出来了~

  • 相关阅读:
    ValueError: Layer conv2d_1 was called with an input that isn't a symbolic tensor. Received type: <class 'tuple'>. Full input: [(600, 600, 3)]. All inputs to the layer should be tensors.
    OSError: `pydot` failed to call GraphViz.Please install GraphViz (https://www.graphviz.org/) and ensure that its executables are in the $PATH.该错误的解决
    numpy操作1--任务一:单通道图像转三通道理解/任务二:按axis=0或axis=1或axis=2(轴)堆叠(stack)
    探究灰度图像对目标检测测试结果影响----RGB转灰度图像、灰度图像扩充成三通道
    git项目上传github
    jupyter中,ipynb文件转pdf文件
    面试-操作系统
    数据库-面试
    面试—计算机网络
    PE文件结构
  • 原文地址:https://www.cnblogs.com/erniu/p/4239683.html
Copyright © 2011-2022 走看看