Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

ios - Use of 'self' in property access 'frame' before super.init initializes self

I have this code

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

}

I get an error at the line:

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

The error says Use of 'self' in property access 'frame' before super.init initializes self

I don't have any idea how to solve this.

Please bare in mind I am from an objective - C background and recently started learning swift.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must call super.init() before accessing self within a init() method:

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

Change it to:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...