Post

Replies

Boosts

Views

Activity

How to add UserDefaults to save a table view button status?
I have a table view with a "like" button. Users can tap to like the content in each cell. I want to use UserDefaults to persist the button status so that it gets saved if a user closes the app. I'm a new developer so I was hoping for guidance on getting started. Here is the code for the table view cell: import UIKit class QuotesTableViewCell: UITableViewCell {   @IBOutlet weak var likeButton: UIButton!   @IBOutlet weak var quoteLabel: UILabel!   override func awakeFromNib() {     super.awakeFromNib()     // Initialization code   }   override func setSelected(_ selected: Bool, animated: Bool) {     super.setSelected(selected, animated: animated)     // Configure the view for the selected state   }   @IBAction func likeTapped(_ sender: UIButton) {           if likeButton.tag == 0{       likeButton.setImage(UIImage(named: "GreenHeart"), for: .normal)       likeButton.tag = 1     } else{               likeButton.setImage(UIImage(named: "blankHeart"), for: .normal)       likeButton.tag = 0             }   }     } And here is the code for the view controller: import UIKit class QuotesMainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {       @IBOutlet weak var quotesTableView: UITableView!       let quoteList = ["Quote1", "Quote2", "Quote3"]       override func viewDidLoad() {     super.viewDidLoad()           quotesTableView.delegate = self     quotesTableView.dataSource = self               }           func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {     return quoteList.count   }       func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {     let cell = quotesTableView.dequeueReusableCell(withIdentifier: "cell") as! QuotesTableViewCell           cell.quoteLabel.text = quoteList[indexPath.row] as! String     return cell   }             }
Topic: UI Frameworks SubTopic: UIKit Tags:
7
0
1.2k
Apr ’22