Bright Future Bright Future - 3 months ago 11
Swift Question

How to access properties defined during super class initialization

I'm creating a custom view with 2 image views, and I want to be able to animate from one to another, here's my code:

class FlashCard: UIView {

required init?(coder: NSCoder) {
super.init(coder: coder)

let firstImageView = UIImageView(frame: self.frame)
firstImageView.image = UIImage(named: "Lightning")
addSubview(firstImageView)

let secondImageView = UIImageView(frame: frame)
secondImageView.image = UIImage(named: "Tifa")
addSubview(secondImageView)
secondImageView.isHidden = true

}

func showBack() {
UIView.transition(from: firstImageView, to: secondImageView, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, completion: nil)
}
}


But in my
showBack
function, I got the error: use of unresolved identifier.

How do I properly access
firstImageView
and
secondImageView
?

Answer

There is no need for the image views to be variables, of whatever flavour of optional.

class FlashCard: UIView {

    let firstImageView = UIImageView()
    let secondImageView: UIImageView()

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        firstImageView.frame = frame
        firstImageView.image = UIImage(named: "Lightning")
        addSubview(firstImageView)

        secondImageView.frame = frame
        secondImageView.image = UIImage(named: "Tifa")
        addSubview(secondImageView)
        secondImageView.isHidden = true
    }

    func showBack() {
        UIView.transition(from: firstImageView, to: secondImageView, duration: 1.0, options: UIViewAnimationOptions.transitionCrossDissolve, completion: nil)
    }
}

Properties of a class must be initialised before the super initialiser is called, which is why the other answer used implicitly unwrapped optional variables.

Comments