在super.init初始化self之前,在属性访问"frame"中使用"self" [英] Use of 'self' in property access 'frame' before super.init initializes self

查看:130
本文介绍了在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))

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

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

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

请记住我来自客观的C语言背景,并且最近开始学习敏捷.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆