I've created a Xib file with a UIView and then created a custom UIView class connected to the xibs file owner. However i'm not sure how to create something programatically. I've tried to add the awakeFromNib function however it seems not ro run, what method should implement in order to change backgroundColor programmatically?
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "MediaPlayer", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
You can change backgroundColor of any like this.
self.view.backgroundColor = [UIColor redColor];
Hope this helps.
仅当这样调用UINib
才会调用awakeFromNib
: https : UINib
Your UIView subclass should look like this:
class CustomView : UIView {
@IBOutlet weak var contentView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setup() {
Bundle(for: CustomView.self).loadNibNamed(String(describing: CustomView.self), owner: self, options: nil)
}
}
Custom view in Interface Builder
let view = CustomView()
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.