在Swift中将自定义的UITableViewCell共享给多个UITableViewController

3

目前,我有两个表视图控制器,它们包含一些相同的自定义表格视图单元格。每个表视图控制器都有自己的自定义表格视图单元格。我希望创建一个可以在这两个表视图控制器之间共享的自定义表格视图单元格。有什么指南可以参考吗?

1个回答

6

首先,你可以使用代码创建一个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!
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接