簡體   English   中英

帶有XIB Swift的UITableViewCell子類

[英]UITableViewCell Subclass with XIB 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
    }

}

有沒有辦法在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中創建一個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:設置標簽和文本字段tableView:cellForRowAtIndexPath:可能通過調用NameInput上的實例方法)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM