简体   繁体   English

在Swift中访问存储的闭包的属性

[英]Access to property of a stored closure in Swift

Let's say I have a property that holds a UIView instance like the one in this class: 假设我有一个属性,该属性包含一个类似于此类的UIView实例:

class MyViewController: UIViewController {
    var myView: UIView = {
        let view = UIView()
        let label = UILabel()
        view.addSubview(label)
        return view
    }()
}

Is there any way I can access its label property from the view controller? 有什么方法可以从视图控制器访问其label属性?

class MyViewController: UIViewController {
    // myView declaration goes here
    func changeLabel() {
         myView.label.text = "Help!"
    }
}

The compiler tells me that UIView doesn't have a label member which is true. 编译器告诉我, UIView没有真正的label成员。 Is there any way to actually change the label text of the closure declared above? 有什么方法可以实际更改上面声明的闭包的标签文本?

Yes you can! 是的你可以!

First, your first code snippet does not compile, it should be changed to: 首先,您的第一个代码段未编译,应更改为:

var myView: UIView = {
    let view = UIView()
    let label = UILabel()
    view.addSubview(label)
    return view
}() // <- add these parentheses

Now, to access label , we need to give the label a tag , so do this: 现在,要访问label ,我们需要给label一个tag ,所以可以这样做:

var myView: UIView = {
    let view = UIView()
    let label = UILabel()
    label.tag = 1
    view.addSubview(label)
    return view
}()

Now you can access the label in your VC like this: 现在,您可以像下面这样在VC中访问标签:

let label = myView.viewWithTag(1) as! UILabel

If your view only has one subView, such as the one in the example that you are using, it's really easy to achieve by using the subviews property. 如果您认为只有一个子视图,如一个在您正在使用的例子,它真的很容易使用,实现subviews属性。 This returns an array of UIView (in this case it will have only one element) and there you can find your label and change the text. 这将返回一个UIView数组(在这种情况下,它将只有一个元素),您可以在其中找到标签并更改文本。

If your view is more complex and has several subviews, this can get trickier, since you'll have to iterate through the subviews array and get the corresponding one. 如果您的视图更复杂并且有多个子视图,则这将变得更加棘手,因为您必须遍历subviews数组并获取相应的子视图。 This would lead to the use of tags and may not be the best solution for complex situations. 这将导致使用标签,并且可能不是复杂情况下的最佳解决方案。

Another solution would be to make a simple subclass of UIView where you add a method which can be something similar to addLabel and there you save a reference to that label in a property. 另一个解决方案是制作UIView的简单子类,在其中添加一个方法,该方法可以类似于addLabel然后在其中将对该标签的引用保存在属性中。 Afterwards you can access it easily. 之后,您可以轻松访问它。

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

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