在之前的文章中:Swift - 修改tableView分组(section)头部、尾部的字体颜色和大小。我介绍了如何通过纯代码的方式来自定义表格(tableView)里每个分组(section)的 header和 footer。但如果要实现的样式比较复杂,那么使用纯代码实现就会比较麻烦,这时我们还可以借助 xib 来实现。
下面演示如何使用 xib 来自定义 section 的 header 和 footer,对于自定义整个 tableView 的 header 和 footer 的原理也一样的。
1,样例效果图
我们将分组头背景色改成绿色,文字改成白色。同时在文字前面添加了个图标。
2,创建自定义的分组头
(1)首先新建一个 XIB 文件(带有 View 的),名叫 MyTableViewSectionHeader
(2)将 xib 文件中 View 的 Size 修改为 Freedom,Status bar 修改为 None。并将其调整成合适的尺寸。
(3)在 View 中添加一个 UIImage 和一个 UILabel,分别用来显示图标和分组标题。并设置好它们的相关属性和约束。
(4)选择 Label,将其 Tag 设置为 1。后面使用时通过这个 tag 来取得标签并进行赋值。
由于这个自定义的分组头比较简单,所以我这里只需要创建一个 xib 文件就够了。不需要再在创建对应实现类。
关于 xib 如何关联对应的 UIView 类,可以参考我之前的这篇文章:Swift - XIB结合UIView制作自定义组件(xib加载绘制UIView)
3,使用自定义的分组头
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
源码下载:hangge_1392.zip
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_1392.html