0

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
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • How are the views being initialized when you use them? Are they being initialized using the .xib or are they using an init() function? – keithbhunter Aug 10 '15 at 12:30

3 Answers3

0

You can change backgroundColor of any like this.

self.view.backgroundColor = [UIColor redColor];

Hope this helps.

Bharat Nakum
  • 647
  • 6
  • 18
0

awakeFromNib will be called only if call UINib like this: https://stackoverflow.com/a/25513605/846780

Community
  • 1
  • 1
Klevison
  • 3,342
  • 2
  • 19
  • 32
  • are you sure that `let view` is not nil? – Klevison Aug 10 '15 at 12:51
  • not really however it shows my xib file in the view, so i guess it is not? – Peter Pik Aug 10 '15 at 12:56
  • So you need to investigate.. What you did should call `override func awakeFromNib()` method. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSNibAwaking_Protocol/#//apple_ref/occ/instm/NSObject/awakeFromNib – Klevison Aug 10 '15 at 13:05
0
  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()
Abel C
  • 62
  • 4