简体   繁体   中英

programmatically customize UIView in xib

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才会调用awakeFromNibhttps : UINib

  1. Create your custom view .xib file
  2. Create a .swift file subclass of UIView
  3. Set file's owner to your subclass

Set files owner

  1. Drag the file's view into .swift file and call it contentView

Connect IBOutlet

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)
  }
}
  1. Now you can use your subclass directly in Interface Builder

Custom view in Interface Builder

  1. Or programatically

Custom view programatically

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM