Reputation: 15
IBOutlets in CustomView are coming as nil.
I have created Custom view(xib).
Please find images for more information.
class TextFieldView: UIView {
@IBOutlet var contentView: TextFieldView!
@IBOutlet weak var customTextField: UITextField!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var placeHolderLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func awakeFromNib() {
super.awakeFromNib()
}
func commonInit()
{
let bundle = Bundle(for: type(of: self))
bundle.loadNibNamed("TextFieldView", owner: self, options: nil)
customTextField.backgroundColor = UIColor.green
NSLog("Called")
}
Still throwing an error with exc_bad_access.(In loadNibNamed line of code)
Upvotes: 1
Views: 2919
Reputation: 634
Swift 3 Version
This is the solution that worked for me. Make sure your file object in IB has the TextFieldView Class assigned to it (not the UIView itself). Also make sure all your IBOutlets are connected to the right place or you risk running into trouble.
class TextFieldView: UIView {
@IBOutlet var contentView: TextFieldView!
@IBOutlet weak var customTextField: UITextField!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var placeHolderLabel: UILabel!
override init (frame: CGRect) {
super.init(frame: frame)
commonInit()
}
//This lets us use TextFieldView in IB
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle(for: TextFieldView.self).loadNibNamed("TextFieldView", owner: self, options: nil)
//Positioning content so it fills view space
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addSubview(contentView)
}
Upvotes: 1
Reputation: 22946
You need something like:
/// This view must be connected with the main view of the XIB.
@IBOutlet private var view: UIView!
/// This method is used when creating an `ApexView` with code.
override init(frame: CGRect)
{
super.init(frame: frame)
initView()
}
/// This method is called when instantiated from a XIB.
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initView()
}
private func initView()
{
/// Fill in the name of your XIB. I assumed it `"TextFieldView"`.
Bundle.main.loadNibNamed("TextFieldView", owner: self, options: nil)
self.view.frame = CGRect(x: 0.0, y: 0.0, width: self.width, height: self.height)
self.addSubview(self.view!)
...
}
Upvotes: 0