在 super.init 初始化 self 之前在属性访问“frame"中使用“self" [英] Use of 'self' in property access 'frame' before super.init initializes self
本文介绍了在 super.init 初始化 self 之前在属性访问“frame"中使用“self"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码
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))
错误说在super.init初始化self之前在属性访问'frame'中使用'self'
我不知道如何解决这个问题.
I don't have any idea how to solve this.
请记住,我来自客观 - C 背景,最近开始学习 swift.
Please bare in mind I am from an objective - C background and recently started learning swift.
推荐答案
在 init() 中访问
self
之前,您必须调用 super.init()
方法:
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))
}
改为:
init(imageView: UIImageView) {
super.init(frame: CGRect(origin: CGPoint.zero, size: imageView.frame.size))
self.imageView = imageView
}
这篇关于在 super.init 初始化 self 之前在属性访问“frame"中使用“self"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文