Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating Button Title w/ Boolean Variable Swift

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading