简体   繁体   中英

How to use a custom UITableViewCell with xib without a UITableView

I have created a custom UITableViewCell named CustomTableViewCell having xib.

The code for the CustomTableViewCell is as follows-

class CustomTableViewCell: UITableViewCell {
    @IBOutlet weak var label1: UILabel!
}

In a UITableViewController , I use the CustomTableViewCell as follows-

  • in viewDidLoad() , the register(_:forCellReuseIdentifier:) is called.

  • in tableView(_:cellForRowAt:) function, the dequeueReusableCell(withIdentifier:for:) is called and the text for the label1 is set.

The code works as expected and the CustomTableviewCell is visible when the app is run.

There is another custom UIViewController with xib. To this xib file, I would like to add the CustomTableViewCell as a subView.

I added a UIView to the xib and set it's class to CustomTableViewCell . When the app is run, the app crashes because the label IBOutlet is nil.

Can anyone point out how to fix this issue?

要添加自定义 UIViewcell ,您可以使用 xib 创建 uiviewcell 并为特定单元格提供可重用标识符..然后在 uiviewcontroller 中定义 tableviewcell 时使用该特定 uiview 单元格。

The thing you are trying to do is achieveable but in a different way. UITableView cells are automatically instantiated by UITableViews only. So by setting the class name won't instantiate the CustomTableViewCell.

The solution is: Every UITableView cells are subclass of UIView, so what we can do is instantiate the CustomTableView cell ourself through nib and add the view programmatically in a container view which we can put in the UIViewController.

Here is the code that might help you.

import UIKit

class ViewController: UIViewController {
   @IBOutlet weak var containerView: UIView!

   override func viewDidLoad() {
     super.viewDidLoad()

     let nib = UINib(nibName: String(describing: CustomTableViewCell.self), bundle: nil)
     if let customTableViewCell = nib.instantiate(withOwner: self, options: nil).first as? CustomTableViewCell {
        customTableViewCell.label1.text = "Hello"
        containerView.addSubview(customTableViewCell)
     }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM