7

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.

shallowThought
  • 19,212
  • 9
  • 65
  • 112
Aryan
  • 95
  • 1
  • 1
  • 7
  • what value is `self.frame.size.width` supposed to have? Just replace it with `0` when calling `super.init` – luk2302 Jan 21 '17 at 12:19
  • i know that it doesnt give error but i want the value to be the self.frame.size.width. @luk2302 – Aryan Jan 21 '17 at 12:21
  • 1
    You are not making any sense. What value are you expecting it to return? Think about it this way: `frame` is initialized in `super.init`, it does not *exist* yet where you are trying to use it. – luk2302 Jan 21 '17 at 12:22

1 Answers1

11

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 
}
shallowThought
  • 19,212
  • 9
  • 65
  • 112