William  Sterling William Sterling - 1 year ago 88
Objective-C Question

objc custom view with nib not visible on tableviewcell

I have an UITableViewCell contain a custom view, the custom view contains two label. The view hierarchical likes that:

|---Label 1
|---Label 2

But run application, just shown 'MyView', Label 1 and Label 2 not visible! If I wrote code on viewDidLoad, take 'MyView' as viewController.view's subview, the label 1 and 2 is appeared. Hope you can help me.
enter image description here

Answer Source

Have you tried this?

Create MyView like this:

class MyView: UIView {

@IBOutlet weak var _label1: UILabel!
@IBOutlet weak var _label2: UILabel!

// Our custom view from the XIB file
var view: UIView!

//MARK: - Setup -
private func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    // Make the view stretch with containing view
    view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

private func loadViewFromNib() -> UIView {

    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "MyView", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

    return view

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

override func awakeFromNib() {


func setLabeles(lbl1: String, lbl2: String) {
    _label1!.text = lbl1
    _label2!.text = lbl2

enter image description here Make Label1 and Label2 outlet to respective ones.

Then add it to custom tableViewCell as:

enter image description here (Pink colour is for highlighting!) Make My View outlet.

Custom cell code:

@IBOutlet weak var _myView: MyView!

class func identifier() -> String {
    return "CustomTableViewCellId"

class func nib() -> UINib {
    let nib = UINib(nibName: "CustomTableViewCell", bundle: NSBundle.mainBundle())
    return nib

//MARK: Public Methods
func setCellIndexLabel(index: Int) {
    _myView!.setLabeles("lbl1: \(index)", lbl2: "lbl2: \(index)")

Then there is no need to do extra anything in table view, just do: In viewDidLoad()-

tableView!.registerNib(CustomTableViewCell.nib(), forCellReuseIdentifier: CustomTableViewCell.identifier())
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // Configure the cell...
    let cell = tableView.dequeueReusableCellWithIdentifier(CustomTableViewCell.identifier(), forIndexPath: indexPath) as! CustomTableViewCell

    return cell

And you will get this:

enter image description here

Is this what you are looking for?

Forgive me for providing swift code, but it's not much different that objective-c!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download