今天,我意识到对于 MVC,我们可以构建 Model
并且可以使用我们的 Controller
。但是,我似乎没有尝试设计自己的View
,而是使用IOS SDK 提供的默认View
。
你能和我一起考虑这个例子吗: 考虑 tableView 的 Header,
1.我想在里面放一个按钮
2. 并使页眉更大以包含一些详细信息标签。
3.同时让Header的背景变成UIColor.blueColor()
我尝试创建一个类(称为 MyHeaderView
)扩展 UITableViewHeaderFooterView
,我知道我的 MyTableViewController
中有一个属性是 Header
的条目,我可以分配一个新的我自己的设计类对象 -- MyHeaderView
。我对吗?这就是我的想法,但我只是尝试了第三个要求(将背景更改为蓝色):
在 MyHeaderView
中,我定义了一个函数:
class MyHeaderView: UITableViewHeaderFooterView {
func change(){
self.backgroundColor = UIColor.blackColor()
}
}
里面
class MyTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRectMake(0, 0, 1000, 1000)// Big enough!
var a = MyHeaderView(frame: frame)
a.change()
self.view.addSubview(a)// To be frank, I believe this statement is not right for achieving this requirement
}
}
Could anyone tell me a little about how to customise my own view! Thank you! (IF I my not clear myself, please help me point it out:D I will make it more detail as soon as possible)
最佳答案
我认为您可能有兴趣阅读 Matt Neuburg 撰写的“Programming iOS 9”一书,尤其是“Table Views and Collection Views”子章。
节页眉或页脚分别出现在单元格之间、节的第一行之前或节的最后一行之后。
不要将节页眉和页脚与整个表格的页眉和页脚混淆。后者是 TableView 本身的 View 属性,它的 tableHeaderView 和 tableFooterView。表格标题仅在表格一直向下滚动时出现;只有当表格一直向上滚动时才会出现表格页脚。
因此,回到您自定义表格部分 View 的尝试(我假设的),您可能会发现这些提取的信息很有用:
UITableViewHeaderFooterView 类是一个 UIView 子类,专门用作页眉或页脚的 View ;很像表格 View 单元格,它是可重用的。它具有以下属性:
- textLabel - 用于显示标题文本的标签 (UILabel) 或 页脚。
- detailTextLabel - 如果您设置其文本,此标签仅出现在分组样式表中。
- contentView - 页眉或页脚的 subview ,您可以向其添加自定义 subview 。如果这样做,您可能不应该使用内置的 textLabel; textLabel 不在 contentView 中,从某种意义上说不属于您。
- backgroundView - 您要分配的任何 View 。 contentView 在 backgroundView 的前面。 contentView默认背景是透明的,所以backgroundView会透出来。另一方面,不透明的 contentView.backgroundColor 会完全遮挡 backgroundView。如果 backgroundView 为 nil(默认值),则页眉或页脚 View 将提供自己的背景 View ,其 backgroundColor 是从表格的 backgroundColor 派生的(以某种恼人的未指定方式)。
您实现委托(delegate)方法tableView:viewForHeaderInSection: 或 tableView:viewForFooterInSection:(或两者)。您提供的 View 用作整个页眉或页脚,并自动调整大小以适应表格的宽度和部分页眉或页脚的高度。
您不需要返回 UITableViewHeaderFooterView,但您可能想要返回,以便利用可重用性。为此,该过程很像使电池可重复使用。您可以通过调用 registerClass:forHeaderFooterViewReuseIdentifier: 预先注册表格 View 。要提供可重用 View ,请发送 TableView dequeueReusableHeaderFooterViewWithIdentifier:;结果将是新实例化的 View 或重用的 View 。
此外,两对委托(delegate)方法允许您对页眉或页脚 View 执行最终配置:
tableView:willDisplayHeaderView:forSection:
tableView:willDisplayFooterView:forSection:
和
tableView:heightForHeaderInSection:
tableView:heightForFooterInSection:
作为奖励,Matt 警告的另一个怪癖是:
不要设置 UITableViewHeaderFooterView 的 backgroundColor;相反,设置其 contentView 的 backgroundColor,或分配一个 backgroundView 并根据需要进行配置。此外,设置它的 tintColor 没有任何效果。
关于ios - 如何在 IOS 中使用 Swift 设计自己的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656238/