Aneesh Poddutur
Aneesh Poddutur

Reputation: 29

How do I get and store an initial value of a property of a UIView?

I have a UIView laid out and constrained in main.storyboard, and have an IBOutlet connecting it to its corresponding ViewController class in ViewController.swift.

I need to manipulate the position of the view in various different functions, and to do this I need to be able to access the value of the initial y-position of the view. I tried to do this using

public let inputRest = self.userInputView.frame.origin.y

in the body of the ViewController class. However, this gives me the error Cannot use instance member 'userInputView' within property initializer; property initializers run before 'self' is available.

How do I store properties of instance members in variables in order to call them in a function? Is there a way to declare this variable in viewDidLoad() and access it in other functions?

Thanks for the help.

Upvotes: 0

Views: 254

Answers (1)

Bergasms
Bergasms

Reputation: 2203

You cannot declare it as a class level property because it won't be created until the ViewController is instantiated. I think what you want to do is as follows.

//instantiate with an initial value of 0.0 
public var inputRest : CGFloat = 0.0 

override func viewDidLoad() {
    super.viewDidLoad()

    //you can do this here, because the userInputView will have been created
    self.inputRest = self.userInputView.frame.origin.y
}

This is an inherent limitation of ViewControllers which are instantiated from a storyboard not being able to have let properties which can only be defined once. There are ways around this by overwriting the constructor used to create the view controller from the coder, but it's a lot of work, not easy to read, and very much a lot of work for nothing.

Upvotes: 1

Related Questions