我有这段代码
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。
答案 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
}