When I try to use this custom control within my main view controller, by dragging a UIView onto screen in IB and setting it to "CustomerControlView", it doesn't actually show it.
Question - What is wrong with the code I have here?
Background - So wanting to basically: a) design a customer control in IB b) so I'm assuming I create the NIB file and then create a UIView file, so this is what I've done
Screenshot of NIB & swift file
import UIKit
class CustomControlView: UIView {
// @IBOutlet var icon: UIImageView!
// @IBOutlet weak var view: UIView!
@IBOutlet weak var button: UIButton!
@IBOutlet weak var text1: UITextField!
@IBOutlet weak var text2: UITextField!
override init(frame: CGRect) {
print("override init(frame: CGRect) ")
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
print("required init?(coder aDecoder: NSCoder)")
super.init(coder: aDecoder)
// let arr = NSBundle.mainBundle().loadNibNamed("CustomControlView", owner: nil, options: nil)
// let v = arr[0] as! UIView
// self.view.addSubview(v)
}
}
Snapshot showing how I have included the custom view into my main viewController view:
Just add @IBDesignable
above the class line to tell Xcode to compile it before showing it in storyboard. There is a great discussion on this subject here: http://nshipster.com/ibinspectable-ibdesignable/
Also, you need to make sure that the NIB is being loaded:
override init(frame: CGRect) {
print("override init(frame: CGRect) ")
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
print("required init?(coder aDecoder: NSCoder)")
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CustomNumberPad", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}