Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Assign a NIB to self in class

I am creating a UIView subclass for a notification dropdown banner. I am using a XIB to build out the view and want to assign that xib to the class when it initializes (i.e. avoiding having to do this from the calling ViewController).

Since you can't assign to 'self' in swift, how do I properly do this from within the class itself?

class MyDropDown: UIView
{
     func showNotification()
     {
          self = UINib(nibName: nibNamed, bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIView
     }
}
like image 494
JimmyJammed Avatar asked Dec 11 '22 01:12

JimmyJammed


1 Answers

For anyone looking on how to initialize a xib from it's own class in swift, here is the best approach using a custom class initializer:

class MyCustomView: UIView
{
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    class func initWithTitle(title: String, image: UIImage? = nil) -> MyCustomView
    {
        var myCustomView = UINib(nibName: "MyCustomView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? MyCustomView

        myCustomView.titleLabel.text = title

        if image != nil
        {
            myCustomView.imageView.image = image
        }

        //...do other customization here...
        return myCustomView
    }
}
like image 176
JimmyJammed Avatar answered Dec 13 '22 15:12

JimmyJammed