问题描述
我有一个 UITableViewCell
子类 NameInput
连接到带有自定义 init的xib
方法。
I have a UITableViewCell
subclass NameInput
that connects to an xib with a custom init
method.
class NameInput: UITableViewCell {
class func make(label: String, placeholder: String) -> NameInput {
let input = NSBundle.mainBundle().loadNibNamed("NameInput", owner: nil, options: nil)[0] as NameInput
input.label.text = label
input.valueField.placeholder = placeholder
input.valueField.autocapitalizationType = .Words
return input
}
}
我有没有办法在 viewDidLoad $中初始化这个单元格c $ c>方法仍然可以重用它?或者我是否必须使用重用标识符注册类本身?
Is there a way I can initialize this cell in the viewDidLoad
method and still reuse it? Or do I have to register the class itself with a reuse identifier?
推荐答案
习惯的NIB过程是:
-
使用重用标识符注册NIB。在Swift 3中:
Register your NIB with the reuse identifier. In Swift 3:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
}
在Swift 2中:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
}
定义您的自定义单元格类:
Define your custom cell class:
import UIKit
class NameInput: UITableViewCell {
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
}
在Interface Builder中创建一个NIB文件(带有步骤1)中引用的相同名称:
Create a NIB file in Interface Builder (with the same name referenced in step 1):
-
指定NIB中tableview单元格的基类以引用自定义单元格class(在步骤2中定义)。
Specify the base class of the tableview cell in the NIB to reference your custom cell class (defined in step 2).
将NIB中单元格中的控件之间的引用连接到 @IBOutlet
自定义单元格类中的引用。
Hook up references between the controls in the cell in the NIB to the @IBOutlet
references in the custom cell class.
您的 cellForRowAtIndexPath然后
将实例化单元格并设置标签。在Swift 3中:
Your cellForRowAtIndexPath
would then instantiate the cell and set the labels. In Swift 3:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! NameInput
let person = people[indexPath.row]
cell.firstNameLabel.text = person.firstName
cell.lastNameLabel.text = person.lastName
return cell
}
在Swift 2中:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NameInput
let person = people[indexPath.row]
cell.firstNameLabel.text = person.firstName
cell.lastNameLabel.text = person.lastName
return cell
}
我从你的例子中不完全确定你在你的单元格上放置了什么控件,但上面有两个 UILabel
控件。连接 @IBOutlet
引用对您的应用有意义。
I wasn't entirely sure from your example what controls you placed on your cell, but the above has two UILabel
controls. Hook up whatever @IBOutlet
references make sense for your app.
这篇关于带有XIB Swift的UITableViewCell子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!