目前,我有两个表视图控制器,它们包含一些相同的自定义表格视图单元格。每个表视图控制器都有自己的自定义表格视图单元格。我希望创建一个可以在这两个表视图控制器之间共享的自定义表格视图单元格。有什么指南可以参考吗?
目前,我有两个表视图控制器,它们包含一些相同的自定义表格视图单元格。每个表视图控制器都有自己的自定义表格视图单元格。我希望创建一个可以在这两个表视图控制器之间共享的自定义表格视图单元格。有什么指南可以参考吗?
首先,你可以使用代码创建一个UITableViewCell
:(你也可以在.xib
文件中设计你的单元格视图 - 详见这里)
// MyCell.Swift
import UIKit
import Foundation
class MyCell: UITableViewCell {
// do whatever you want to customize the cell
}
然后在你的两个UITableViewController
类中,分别在viewDidLoad
方法中注册你自定义的UITableViewCell
类。
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(MyCell.self as AnyClass, forCellReuseIdentifier: "cell")
}
然后在cellForRowAtIndexPath
函数中创建/重复使用此自定义单元格:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: MyCell? = self.tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCell
if cell == nil {
// if the cell is not yet created in the system, create a new cell object
cell = MyCell(style: .default, reuseIdentifier: "cell")
}
// customize your cell...
cell.textLabel?.text = "Your Label Text"
return cell!
}