I'm new to Swift. I would like to know if possible add a "favorite" Button programmatically inside a view controller that inherits from UITableView? I need to say too that I wanna use this button to favorite a result from google API. This is possible once the result comes from a search's result and not from a specific list? PS: I'm doing my project in UIKIT. Thank you.
CodePudding user response:
Of course your view controller will then inherit from UITableViewController
, not UITableView
.
Here are the basics:
var favoriteButtonItem: UIBarButtonItem?
var isFavorite: Bool = <...initial value...>
var favoriteImage
{
return UIImage(systemName: "heart" (isFavorite ? ".fill" : ""))
}
favoriteButtonItem = UIBarButtonItem(image: favoriteImage,
style: .plain,
target: self,
action: #selector(toggleFavorite))
navigationItem.rightBarButtonItem = favoriteButtonItem
@objc private func toggleFavorite()
{
isFavorite = !isFavorite
favoriteButtonItem.image = favoriteImage
<...logic to process change...>
}
You'll need to add logic to disable or not show yet favoriteButtonItem
until the backend has returned the current value.