简体   繁体   中英

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:

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?

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. 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:

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:

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. 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.

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. 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. Afterwards you can access it easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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