ios - 在其父类(super class)初始化之后初始化 UIView init?

标签 ios swift xcode uiview initialization

查看斯坦福 iOS 9 类(class)中的讲座幻灯片 here ,他正在创建一个带有两个初始化器的新 UIView(一个是从 Storyboard创建的 UIView,另一个是在代码中创建的)。以下代码写在该特定幻灯片的底部:

    func setup() {....}  //This contains the initialization code for the newly created UIView

    override init(frame: CGRect) {  //Initializer if the UIView was created using code.
        super.init(frame: frame)
        setup()
    }
    required init(coder aDecoder: NSCoder) {  //Initializer if UIView was created in storyboard
        super.init(coder:aDecoder)
        setup()
    }

规则是您必须先初始化所有自己的属性,然后才能从父类(super class)中获取初始化。那么,为什么在这种情况下他会在初始化自己 setup() 之前调用他的父类(super class) init super.init?这是否与以下规则相矛盾:

Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.

最佳答案

我还没有看到这个例子中的所有其余代码,但规则只是在调用 之前必须初始化您的属性(即它们占用的内存必须设置为某个初始值) super.init(),并不是说你不能运行额外的设置代码。

您甚至可以通过声明您的属性 lazy var 或使用自动初始化为 >无。然后,您可以在调用 super.init() 后设置它们。

例如:

class Foo: UIView {
    var someSubview: UIView!  // initializes automatically to nil

    lazy var initialBackgroundColor: UIColor? = {
        return self.someSubview.backgroundColor
    }()

    init() {
        super.init(frame: .zero)
        setup()          // do some other stuff
    }

    func setup() {
        someSubview = UIView()
        someSubview.backgroundColor = UIColor.whiteColor()
        addSubview(someSubview)
    }
}

关于ios - 在其父类(super class)初始化之后初始化 UIView init?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759412/

相关文章:

xcode - 使用Xcode 8.1提交应用商店

ios - UIPanGestureRecognizer 拖动 ImageView - 如果我第二次拖动,比例会放大

ios - 在另一个 View Controller 中调用方法,但不继续调用它?

ios - 将泛型 AnyObject 向下转换为协议(protocol)关联类型 Self.Model

iphone - 解释 alloc/init 发生两次

swift - Swift 是否有空合并运算符?如果没有,自定义运算符的示例是什么?

iphone - 重新加载表的数据

swift - 返回 Vapor 3 中的部分对象

ios - "No such module ' Alamofire '"Xcode 无法识别 Alamofire 框架

iphone - .NIB -> .XIB 怎么了?