【发布时间】:2017-10-11 14:56:41
【问题描述】:
我有大约 3 或 4 个表格控制器,它们都将使用相同的表格视图单元格。我继续回到第四个可能的逻辑。假设两者之间的信息相同,我可以在多个 tableView 控制器中使用相同的 tableViewCell 吗?还是我必须为每个控制器创建一个新单元?
【问题讨论】:
标签: xcode uitableview
我有大约 3 或 4 个表格控制器,它们都将使用相同的表格视图单元格。我继续回到第四个可能的逻辑。假设两者之间的信息相同,我可以在多个 tableView 控制器中使用相同的 tableViewCell 吗?还是我必须为每个控制器创建一个新单元?
【问题讨论】:
标签: xcode uitableview
是的,你可以。
我假设您使用的是 Swift。
转到文件 -> 新建并选择 cocoaTouch 类,如下所示。
现在为自定义单元格命名您的类,并使其成为 UITableViewCell 的子类。还要选中“同时创建 Xib 文件”框
现在在此 Xib 中设计您的单元格并在其 .Swift 文件中创建插座。假设您有一个看起来像这样的自定义 tableView 单元格
其中包含标签或 ImageView 或单元格中的任何内容。现在在您的自定义单元格的 swift 文件中,您可以编写这样的方法
class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> YourCustomTableViewCell {
let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
tableView.registerNib(UINib(nibName: "YourCustomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
let cell = tableView.dequeueReusableCellWithIdentifier(kYourCustomTableViewCellIdentifier, forIndexPath: indexPath) as! YourCustomTableViewCell
return cell
}
现在您可以在应用程序的任何 tableView 中使用此单元格,如下所示
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = YourCustomTableViewCell.cellForTableView(tableView, atIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
// do something with your cell
}
希望对你有帮助。
Swift 3 和 Swift 4 更新:
class func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> YourCustomTableViewCell {
let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
tableView.register(UINib(nibName: "YourCustomTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
let cell = tableView.dequeueReusableCell(withIdentifier: kYourCustomTableViewCellIdentifier, for: indexPath) as! YourCustomTableViewCell
return cell
}
【讨论】:
是的,您可以在多个 tableView 控制器中使用表格视图单元格。
【讨论】: