与XIB Swift的UITableViewCell子类

我有一个UITableViewCell子类NameInput ,通过一个自定义的init方法连接到一个xib。

 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方法中初始化这个单元格,并仍然可以重用它? 还是必须使用重用标识符注册类本身?

习惯上的NIB过程是:

  1. 用重用标识符注册您的NIB。 在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") } 
  2. 定义您的自定义单元类:

     import UIKit class NameInput: UITableViewCell { @IBOutlet weak var firstNameLabel: UILabel! @IBOutlet weak var lastNameLabel: UILabel! } 
  3. 在Interface Builder中创build一个NIB文件(与步骤1中引用的名称相同):

    • 在NIB中指定tableview单元格的基类以引用您的自定义单元类(在步骤2中定义)。

    • 将NIB单元中的控件之间的引用连接到自定义单元类中的@IBOutlet引用。

  4. 您的cellForRowAtIndexPath然后将实例化单元格并设置标签。 在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引用对您的应用程序的意义。

你不要在viewDidLoad初始化单元格。 你应该用你的表格视图注册XIB,而不是类。 你应该在tableView:cellForRowAtIndexPath:设置标签和文本字段(可能通过在NameInput上调用一个实例方法)。