【问题标题】:Use of 'self' in property access 'frame' before super.init initializes self在 super.init 初始化 self 之前,在属性访问“frame”中使用“self”
【发布时间】:2017-01-21 12:15:21
【问题描述】:

我有这个代码

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

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

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

【问题讨论】:

  • self.frame.size.width 应该有什么价值?调用super.init时只需将其替换为0
  • 我知道它不会给出错误,但我希望该值是 self.frame.size.width。 @luk2302
  • 你没有任何意义。你期望它返回什么价值?可以这样想:framesuper.init 中初始化,它在您尝试使用它的地方不存在

标签: ios swift swift3


【解决方案1】:

init() 方法中访问self 之前,您必须调用super.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 
}

【讨论】:

  • 这没有任何意义。 self.frame 中有什么内容?
  • 必须调用超类 'UIView' 的指定初始化程序我得到这个错误
  • @shallowThought 现在,您可以直接用正确的帧调用super.init(frame: ),而不是用CGRect.zero 调用然后更改它。
  • @shallowThought 小意思,CGRect也可以初始化为CGRect(origin: CGPoint.zero, size: imageView.frame.size)
  • 为什么不使用 frame: imageView.bounds? bounds 是局部坐标系 (0,0,widt,height),frame 是其父视图坐标系 so (x,y,width,height)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多