在super.init初始化self之前,在属性访问'frame'中使用'self'

时间:2017-01-21 12:15:22

标签: ios swift swift3

我有这段代码

import UIKit

class CardView: UIView {

    @IBOutlet var imageView: UIImageView!

    init(imageView: UIImageView) {
        self.imageView = imageView
        super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width, height: self.frame.size.height))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

我在该行收到错误:

super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width, height: self.frame.size.height))

错误说Use of 'self' in property access 'frame' before super.init initializes self

我不知道如何解决这个问题。

请记住,我来自客观 - C背景,最近开始学习swift。

1 个答案:

答案 0 :(得分:5)

super.init()方法中访问self之前,您必须致电init()

init(imageView: UIImageView) {
    self.imageView = imageView /*you are accessing self here before calling super init*/
    super.init(frame: CGRect(x: 0, y:0, width: self.frame.size.width /* here also*/, height: self.frame.size.height))
}

将其更改为:

init(imageView: UIImageView) {
    super.init(frame: CGRect(origin: CGPoint.zero, size: imageView.frame.size))
    self.imageView = imageView 
}