在控制器中添加控件(以UITableView为例)
一般代码添加控件的形式:
- 声明
- 设置frame或者添加布局约束
- 设置数据源 or 代理 and so on
- 添加到view
在开发的过程中,苹果官方文档里面的精神是让我们尽量把一些控件留到需要时才加载进内存的,所以我们尽可能合理利用Lazy延迟加载关键字。
然后我们在控制器中进行一些控件的声明的时候,如果对于需要初始化控件进行比较多的设置的时候,我们可以直接使用闭包的形式进行初始化,这样就能把相关的代码都存放到一起,便于管理。
class ViewController : UIViewController {
lazy var tableView : UITableView = {
let tempTableView = UITableView()
return tempTableView
}()
override func viewDidLoad() {
viewLayout()
viewBasicSetting()
}
//相关控件的布局
func viewLayout(){
tableView.frame = view.bounds
//...
}
func viewBasicSetting(){
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController : UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//创建、设置数据
let cellID = "normal"
var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: cellID)
}
//确定cell有值,强制解包
return cell!
}
}
extension ViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
}
}