类的可重用代码

时间:2016-06-07 12:19:15

标签: ios swift oop

我的应用程序中的几个类执行相同的操作并具有相同的实例变量:

// 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
    }
}

我想避免重复的代码,所以我考虑使用超类,以便所有类继承它。

// 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
    }
}

问题是viewnil,直到笔尖被加载,因此显然不可能称之为超类#&n;方法,因为您传递了一个零对象。我怎么处理这个?

1 个答案:

答案 0 :(得分:2)

这将有效:

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";
    } 
}