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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With