Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nib IBOutlet causes app to crash

Really need your help! I've been through every possible post addressing this issue and nothing seems to work.

So I'm using a .xib file to create a subview within ProfileFoldingCellView.swift, which works perfectly until I attempt to add an IBOutlet in the same class. Here's the code:

import Foundation
import UIKit

class ProfileFoldingCellView: UIView {

    @IBOutlet var mainLabel: UILabel!
    public var cellIndex: Int = 0

    init(index: Int) {
        super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))

        cellIndex = index
        print("Index: \(cellIndex)")

        setupContentView()
    }

    func setupContentView() {
        let contentView = UINib(nibName: "ProfileFoldingCellView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
        contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        addSubview(contentView)
    }

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

}

As you can see, the label IBOutlet is created without any issues and there are no other outdated or unused outlets roaming around.

Label Outlethttp://imgur.com/a/jb9CA

I've also made sure to set ProfileFoldingCellView.swift as the file owner's class.

Everything runs perfectly until I link the outlet! Then I get this error:

Errorhttp://imgur.com/a/6hHPG

Trust me, I've tried everything. I've probably re-created the outlet a million times, nothing is working. Any help would be greatly appreciated!

like image 956
Yoli Meydan Avatar asked May 06 '17 02:05

Yoli Meydan


2 Answers

Leave your File's Owner as NSObject and set your view class as ProfileFoldingCellView, your mainLabel should be connected to the UIView object and not File's Ownerenter image description here

like image 103
janusfidel Avatar answered Oct 06 '22 00:10

janusfidel


I fixed it!

I simply switched the line

let contentView = UINib(nibName: "ProfileFoldingCellView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView

with the following:

let contentView = Bundle.main.loadNibNamed("ProfileFoldingCellView", owner: self, options: nil)?[0] as! UIView

I kept the file owner's class as ProfileFoldingCellView

like image 42
Yoli Meydan Avatar answered Oct 05 '22 23:10

Yoli Meydan