Cesare Cesare - 6 months ago 10
Swift Question

Reusable code for classes

Several classes in my app do the same thing and have the same instance variables:

// one of the many classes I have
// they all load nibs and update the frames of their views
class HelpView: UIView {
@IBOutlet var view: UIView!

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
NSBundle.mainBundle().loadNibNamed("HelpView", owner: self, options: nil)
self.addSubview(self.view)
self.view.frame = self.bounds
}
}


I want to avoid duplicated code, so I thought about using a superclass so that all the classes inherit from it.

// my new superclass all classes will inherit from
class ReusableView: UIView {
@IBOutlet var view: UIView! // all subclasses have different views

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!

// every class has a different nib name
NSBundle.mainBundle().loadNibNamed("Nib name goes here", owner: self, options: nil)
self.addSubview(self.view)
self.view.frame = self.bounds
}
}


The problem is that
view
is
nil
until the nib is loaded, so it's apparently not possible to call that superclass' method because you're passing a nil object. How can I handle this?

Loc Loc
Answer

This will work:

class ReusableView: UIView {

    func getHelperView() -> UIView! {
        preconditionFailure("This method must be overridden") 
    } 

    func getNibName() -> String {
        preconditionFailure("This method must be overridden") 
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        // every class has a different nib name
        NSBundle.mainBundle().loadNibNamed(self.getNibName(), owner: self, options: nil)
        self.addSubview(self.getHelperView())
        self.getHelperView().frame = self.bounds
    }
}

class HelpView: ReusableView {
    @IBOutlet var view: UIView!

    override func getHelperView() -> UIView! {
         return view;
    } 

    override func getNibName() -> String {
         return "NibName";
    } 
}