Updating Button Title w/ Boolean Variable Swift

Advertisements

I’m trying to figure out how to properly configure a follow/unfollow button in a similar fashion to Instagram.

First I’ve created an IBOutlet for the button and used didSet to define its properties:

@IBOutlet weak var followButtonOutlet: UIButton! {
    didSet {
        if !following {
            followButtonOutlet.setTitle("Follow", for: .normal)
            followButtonOutlet.backgroundColor = Colors.indexedPrimary
        } else {
            followButtonOutlet.setTitle("Unfollow", for: .normal)
            followButtonOutlet.backgroundColor = Colors.indexedPrimary
        }
    }
}

Along with the button is a boolean named following, that returns true if the user is on the following list, or false if they’re not:

unc checkIfUserIsFollowing(){
    guard let currentUID = Auth.auth().currentUser?.uid, let userID = user.uid else { return }

    COLLECTION_USERS.document(currentUID).collection("following").document(userID).getDocument { snapshot, err in
        
        if let snapshot = snapshot {
            if snapshot.exists == true {
                self.following = true
            } else {
                self.following = false
            }
        } else {
            print("Error retrieving document: \(err)")
        }
    }
}

The problem I’m having is getting the button title and action to update based on whether or not the user is on the following list. If the user is not being followed, the button should say "Follow", and "Unfollow" if the user is being followed . Whats the proper way to implement this?

>Solution :

You have a didSet on the outlet that attempts to set your button title to follow/unfollow. That logic doesn’t make sense there, since your outlet will get set once when you load your view controller’s views.

You should move that code to a didSet on your following bool. That way, when you change the value of following it will run and update the button appropriately.

Leave a ReplyCancel reply