简体   繁体   中英

How can I call a function only after all properties have been set in my UIView subclass?

I have a UIView subclass somewhat like this:

class AView: UIView {
    var aString = "A String"
    var aBool = true

    override func didMoveToSuperview() {
        func doSomethingWithTheString() {
            if aBool {
                doSomething(withString: aString)
            }
        }
    }
}

Then I add a UIView to a storyboard and set it's class as AView . I link it to my view controller and do this:

@IBOutlet weak var aView: AView!

override func viewDidLoad() {
    aView.aBool = false
    aView.aString = "Another String"
}

The thing is, when doSomethingWithTheString() is called aBool is still true and aString is still "A String" , even though I changed them at viewDidLoad() .

So is there somewhere in AView where I can put doSomethingWithTheString() for it to be called only when all properties have been set? I hoped didMoveToSuperview() would do the trick, but apparently it's still too early.

I thought of calling it in a property's setter, but I don't know which properties will be set and which will be left with their default, and it should only be called when the last property has been set.

Put aString and aBool in a dictionary (aDictionary) then declare

var aDictionary: NSDictionary? {
    didSet{
        doSomethingWithTheString()
    }
}

Of course change a bit the doSomethingWithTheString() to work with the dictionary

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