Create a favorite button that connects to a favorite tableview in swift

4.2k views Asked by At

I was wondering how to create a favorite button in swift that when that button is pressed the object that is "favorited" becomes part of a tableview and stays that way. I hear that core data is a way to do this, but I am still struggling to have the button change when pressed.

When I was creating a button all I get is a button that only changes the first time it presses. An example is I have an empty star button, which means that it is not a favorite, and when i pressed it it changes to a filled heart, which means that it is favorited. When I press the button a second time, when it is currently a filled star, it doesn't change and still remains a filled star.

The other problem that I am having is sending the information from the object to a favorite tableview. I am not sure how to keep something in a tableview as long as the favorite button is switched to filled star.

What I am seeing a lot of is this topic but it is all about making a favorite button in table views. I am not looking for tableviews. An example of what I am trying to do is like a favorite book app. The app opens as a tableview full of books, and when a cell is pressed it opens a new view controller with that book's information, and at the top is a favorite button that is normally an empty star. If I like that book I would like to press that button and the empty star becomes a filled star button, indicating that I like it. The book's information is then sent to a new table view that holds all of the liked books i have done before. If I no longer like that book i would like to press the filled star button again and it is removed from the favorite tableview list.

I am some experience with mysql in regards to swift, and I know that someone people have made comments about using some kind of persistence to save the state of the button.

My biggest problem is that I don't even know where to start. Every attempt I make seems to end the same way, so i don't really have any source code for others to see. I have looked online and through github but the closest thing I could find was a cocoapod named DoButton, but it hasn't been updated in a long time and I am worried that it won't last with another swift update. If someone could lead me in the right path or know a good tutorial, I would greatly appreciate it. If there are any questions I can answer i will answer them to the best of my ability.


Another Update: I managed to get the button to work. It connects to core data and saves the state of the button even when it is quit. Now all that is left is creating a favorite tableView to store the favorites. Here is the code:

class ViewController: UIViewController {

    var buttonIsSelected = false

    var favorites = [Favorite]()



    @IBOutlet var onOffButton: UIButton!
    let image1 = UIImage(named: "empty") as UIImage?
    let image2 = UIImage(named: "filled") as UIImage?




    override func viewDidLoad() {
        super.viewDidLoad()
                print("buttonIsSelected: \(buttonIsSelected)")

    let fetchedRequest: NSFetchRequest<Favorite> = Favorite.fetchRequest()
    do {
        let favorite = try PersistenceService.context.fetch(fetchedRequest)
        for fav in favorite {
            resetAllRecord(entity: fav.favorite)
            buttonIsSelected = fav.favorite
            print("fav.favorite: \(fav.favorite)")
            print("button: \(buttonIsSelected)")
            if fav.favorite == true {
                onOffButton.setImage(image2, for: .normal)
                }
            }
        } catch {
    }
    }


    //button Action
@IBAction func onOffButtonPressed(_ sender: Any) {
    buttonIsSelected = !buttonIsSelected
    if buttonIsSelected == true {
        onOffButton.setImage(image2, for: .normal)
    } else if buttonIsSelected == false {
        onOffButton.setImage(image1, for: .normal)
    }
    saveBool(bool: buttonIsSelected)
}

    //save to core data
func saveBool(bool: Bool) {
    if bool == true {
        print("favorite")
        print("buttonIsSelected \(buttonIsSelected)")
        let liked = Favorite(context: PersistenceService.context)
        liked.favorite = bool
        PersistenceService.saveContext()
        favorites.append(liked)
    } else if bool == false {
        print("unfavorite")
        print("buttonIsSelected \(buttonIsSelected)")
        let liked = Favorite(context: PersistenceService.context)
        liked.favorite = bool
        PersistenceService.saveContext()
        favorites.append(liked)
    }
}

        //clears core data so it doens't get full
func resetAllRecord(entity: Bool) {
    let context = PersistenceService.persistentContainer.viewContext
    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
    do
    {
        try context.execute(deleteRequest)
        try context.save()
    }
    catch
    {
        print ("There was an error")
    }
}

}

1

There are 1 answers

3
AudioBubble On

In the object class create a bool parameter called isFavorite and default set it to false. When the favorite button is pressed the bool should change from false to true. When you have to access only the "favorite" objects, with a for loop iterate through your array of objects and through an if statement check if the isFavorite parameter is true. If it is, the element must be appended to a new object array maybe called favoriteObjects, and there you have all your favorite objects. The rest is pretty straightforward.