是否可以创建一个可以在多个表控制器中使用的tableViewCell?

时间:2016-10-27 03:39:51

标签: xcode uitableview

我有大约3或4个表控制器,它们都将使用相同的tableview单元格。我继续回到可能逻辑的第四个。我可以在多个tableView控制器中使用相同的tableViewCell,假设两者之间的信息是相同的吗?或者我是否必须为每个控制器创建一个新单元格?

2 个答案:

答案 0 :(得分:4)

是的,你可以。

我假设您使用的是Swift。

转到文件 - >新增和选择cocoaTouch类如下。

enter image description here

现在为自定义单元命名您的类,并使其成为UITableViewCell的子类。还要选中“也创建Xib文件”框

enter image description here

现在在此Xib中设计您的单元格并在其.Swift文件中创建出口。假设您有一个自定义的tableView单元格,看起来像这样

enter image description here

其中包含您单元格中的标签或ImageView或anyThing。现在,在自定义单元格的快速文件中,您可以编写一个类似的方法

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
}

答案 1 :(得分:0)

是的,您可以在多个tableView控制器中使用表格视图单元格。

相关问题