ios – 类的可重用代码

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

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

问题是在加载nib之前视图是nil,所以显然不可能调用那个超类’方法,因为你传递了一个nil对象.我怎么处理这个?

最佳答案 这将有效:

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