I have two variables isLoading and isConnected in a UITableViewCell class and the code is as below:
    var isConnected = false {
        didSet {
            if oldValue != isConnected {
                print("[op] isConnected: \(oldValue) -> \(isConnected)")
                updateActionButton()
            }
        }
    }
    private var isLoading = false {
        didSet {
            if oldValue != isLoading {
                print("[op] isLoading: \(oldValue) -> \(isLoading)")
                updateLoadingView()
            }
        }
    }
...
    private func updateActionButton() {
        print("[op] updateActionButton()")
        actionButton.setTitle(isConnected ? "Disconnect" : "Connect", for: .normal)
        actionButton.setTitleColor(isConnected ? .systemRed : .systemBlue, for: .normal)
        print("[op] \(isConnected ? "Disconnect" : "Connect") : \(actionButton.isHidden ? "hidden" : "show")")
    }
    private func updateLoadingView() {
        loadingIndicator.isHidden = !isLoading
        actionButton.isHidden = isLoading
        if isLoading {
            loadingIndicator.startAnimating()
        } else {
            loadingIndicator.stopAnimating()
        }
    }
The logic is very simple:
- When - isLoading == true, the cell will display the- loadingIndicatorwhich is a- UIActivityIndicatorView.
- When - isLoading == false, it will hides the- loadingIndicatorand show the- actionButton.
- When the cell receives a notification, it will change the value of - isLoadingand- isConnected, the code it triggers is:
isConnected = true
isLoading = false
The expected behavior is:
- step 1: The text of button change to Disconnect. (the button is hidden at this time)
- step 2: loadingIndicatoris set to hidden andactionButtonappears with textDisconnect.
However, what it really happens at step 2 is:
actionButton appears with text Connect and then the text changes to Disconnect.
And the console log is:
[op] isConnected: false -> true
[op] updateActionButton()
[op] Disconnect : hidden
[op] isLoading: true -> false
The order I got from console is correct, the setTitle function was called before isLoading changed to false, but I don't know why the text is still Connect when the actionButton.isHidden is set to false.
So I wonder is setTitle asynchronous (the function is not complete when actionButton is set to not hidden)? Or there is something wrong in my code logic to cause the unexpected behavior in step 2?
