带有XIB Swift的UITableViewCell子类

jam*_*ick 9 uitableview ios swift

我有一个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
    }

}
Run Code Online (Sandbox Code Playgroud)

有没有办法在viewDidLoad方法中初始化这个单元格并仍然可以重用它?或者我是否必须使用重用标识符注册类本身?

Rob*_*Rob 54

习惯的NIB流程是:

  1. 使用重用标识符注册NIB.在Swift 3中:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.register(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在Swift 2中:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 定义您的自定义单元格类:

    import UIKit
    
    class NameInput: UITableViewCell {
    
        @IBOutlet weak var firstNameLabel: UILabel!
        @IBOutlet weak var lastNameLabel: UILabel!
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在Interface Builder中创建一个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
    }
    
    Run Code Online (Sandbox Code Playgroud)

    在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
    }
    
    Run Code Online (Sandbox Code Playgroud)

我从你的例子中并不完全确定你对你的细胞有什么控制,但上面有两个UILabel控制.连接@IBOutlet对您的应用程序有意义的任何引用.

  • 我同意你@Rob,但我不使用原型单元的唯一原因是我必须在许多不同的视图控制器中使用这些相同的单元格,所以不是复制和粘贴并且有很多控制器代码,我可以将所有内容保存在单元模型中,并使控制器更清晰,同时提高效率. (2认同)