-2

How do I get all the views in a Nib file? I'm trying to get all the views within a Nib with:

   let objects = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)?[0]  as! NSArray
   let mainView : UIView = objects[0] as! UIView

Though I'm getting this error:

Could not cast value of type 'UIView' (0x108080b40) to 'NSArray' (0x105173c58).

Thanks in advance for your help.

uplearned.com
  • 3,393
  • 5
  • 44
  • 59

1 Answers1

2

loadNibNamed returns array of type [Any]? and your are subscript it using [0], means you are accessing the first object of Array. So just remove [0].

let objects = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)

Second option you can directly initialized UIView object.

if let mainView : UIView = Bundle.main.loadNibNamed("ViewName", owner: self, options: nil)?[0] as? UIView {...}

Choose which ever solution will solved your error.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • Hi I tried both Nirav D and all the labels in the view are not showing up with their data. Also I'm getting a warning on the first option: Cast from '[Any]?' to unrelated type 'NSArray' always fails. -- do you need both the as! in the 2nd option. I tried editing it as it caused an error in Xcode. – uplearned.com Oct 07 '16 at 08:01
  • You are not able to access label because have cast it to `UIView`instead of that you need to cast it with your `customView`also i have edited first option there is no need to cast `[Any]?` to nsarray. – Nirav D Oct 07 '16 at 08:37
  • Thanks Nirav for putting me on the right track I have included edits that worked. Both solutions work. – uplearned.com Oct 08 '16 at 23:27