0

I have a custom view (.xib and .swift) and I want to use it in different ViewControllers and as a custom cellview. the thing is I don't know how to do this :P. can anyone please help me out on how to accomplish this?

my custom view is RestaurantVie, I have labels and images: ` class RestaurantView: UIView {

@IBOutlet var view: UIView!

@IBOutlet weak var imgLogo: UIImageView!
@IBOutlet weak var imgRating: UIImageView!

@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblComments: UILabel!
@IBOutlet weak var lblMinimumOrder: UILabel!
@IBOutlet weak var lblDeliveryCost: UILabel!
@IBOutlet weak var lblStatus: UILabel!

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
    // Drawing code
}
*/

} `

I want to put that in a RestaurantViewcontroller:

` class RestaurantViewController: UIViewController {

@IBOutlet weak var restaurant: RestaurantView!

override func viewDidLoad() {
    super.viewDidLoad()
    let subviewArray = NSBundle.mainBundle().loadNibNamed("RestaurantView", owner: self, options: nil)
    let filtersView : RestaurantView = subviewArray[0] as RestaurantView
    self.view.addSubview(filtersView)

    // Do any additional setup after loading the view.
}

`

But when I run the app, it crashes. showing the message:

* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imgLogo.' * First throw call stack:

etc....

Opticon
  • 3
  • 7

1 Answers1

1

Each view must have an owner. Let say you create a subclass of UIView called CustomView. Then you created the Xib file with the same name.

1) Enter to your Xib file, select the top view, and set the CustomView class in the identity inspector. Now, the view in your Xib file will be linked to your CustomView swift file.

2) To instantiate this view, you need an owner for the view. In most cases, the owner is a view controller, so, in your view controller you can use this snippet:

let subviewArray = NSBundle.mainBundle().loadNibNamed("CustomView", owner: self, options: nil)
let filtersView : CustomView = subviewArray[0] as CustomView
self.view.addSubview(filtersView)

Hope this helps!

lucaslt89
  • 2,431
  • 1
  • 20
  • 30
  • 1
    *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imgLogo.' *** First throw call stack: – Opticon Oct 10 '14 at 16:24