简体   繁体   English

如何获取和存储 UIView 的属性的初始值?

[英]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.我在 main.storyboard 中布置并约束了一个 UIView,并且在 ViewController.swift 中有一个 IBOutlet 将其连接到相应的 ViewController class。

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.我需要在各种不同的函数中操作视图的 position,为此我需要能够访问视图初始 y 位置的值。 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在 ViewController class 的主体中。但是,这给了我错误Cannot use instance member 'userInputView' within property initializer; property initializers run before 'self' is available Cannot use instance member 'userInputView' within property initializer; property initializers run before 'self' is available . 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?如何将实例成员的属性存储在变量中以便在 function 中调用它们? Is there a way to declare this variable in viewDidLoad() and access it in other functions?有没有办法在viewDidLoad()中声明这个变量并在其他函数中访问它?

Thanks for the help.谢谢您的帮助。

You cannot declare it as a class level property because it won't be created until the ViewController is instantiated.您不能将其声明为 class 级别属性,因为在实例化 ViewController 之前不会创建它。 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.这是从 storyboard 实例化的 ViewControllers 的固有限制,不能具有只能定义一次的 let 属性。 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.有一些方法可以通过重写用于从编码器创建视图 controller 的构造函数来解决这个问题,但它需要做很多工作,不容易阅读,而且很多工作都是徒劳的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM