任务1.从Xib加载UIViewcontroller
我们可以加载 UIViewcontroller 表单 Xib 而不是 Storyboard。我们可以使用以下程序:
1.创建一个 UIViewcontroller。
XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your class name , subclass of with UIViewController , check Also create Xib file, language Swift -> Next - Create.
Example: ViewControllerFromXib
2。覆盖 init()。
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: "ViewControllerFromXib", bundle: Bundle.main)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
}
3.打开新创建的Controller
let controller = ViewControllerFromXib.init()
self.present(controller, animated: true, completion: nil)
通过上述方式,我们可以从XIB加载一个UIViewcontroller。
任务 2. 创建一个表格视图并使用自定义 xib 填充它的单元格
1.创建自定义 UItableViewCell
XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your cell name , subclass of with TableViewCell ,检查 Also create Xib file, language Swift -> Next - Create.
示例:CustomTableViewCell
1.为您的 TableView 注册 UItableViewCell。
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Item"
self.tableView.register(UINib(nibName: "CustomTableViewCell", bundle:Bundle.main), forCellReuseIdentifier: "CustomTableViewCell");
}
2。将 UITableViewDataSource 实现到您的视图控制器中
extension ViewControllerFromXib:UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
return cell
}
}
2。将 UITableViewDelegate 实现到您的 Viewcontroller 中。
extension ViewControllerFromXib:UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
return UITableViewAutomaticDimension;
}
}