Skip to main content
 首页 » 操作系统

ios之Swift 初始化之为什么要调用多个 init 函数

2024年01月01日50birdshome

这是我的类,覆盖了 inits

class BottomView: UIView { 
 
    // MARK: - initilization 
 
   override init() { 
        println("init") 
        super.init() 
        setup() 
    } 
 
    override init(frame: CGRect) { 
        println("init frame") 
        super.init(frame: frame) 
        setup() 
    } 
 
    required init(coder aDecoder: NSCoder) { 
        println("init decoder") 
        super.init(coder: aDecoder) 
        setup() 
    } 
 
    func setup() { 
        println("setup") 
    } 
} 

然后我用下面的代码在我的 ViewController 中初始化

class ViewController: UIViewController { 
 
    let bottomView = BottomView() 
 
    override func viewDidLoad() { 
        super.viewDidLoad() 
 
        // Do any additional setup after loading the view, typically from a nib. 
 
        bottomView.frame = CGRectMake(0.0, self.view.frame.height/2.0, self.view.frame.width, self.view.frame.height/2.0) 
        bottomView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleTopMargin 
        self.view.addSubview(bottomView) 
 
    } 
} 

我的输出是

init 
init frame 
setup 
setup 

所以我的问题是,为什么要调用 init(frame:)?

请您参考如下方法:

super.init() 调用 self.init(frame:...)。本质上,这只是他们说 frame 是可选的方式;如果你没有通过它,他们会分配一个 (0,0,0,0) 的框架。

func init() { 
  self.init(frame:CGRectMake(0,0,0,0)); 
}