I display drinks' categories in tableview. In each cell displayed category name and there is a checkbox button. On button click checkbox image appear/disappear.
On the "Apply" button click I want to remember buttons in which cells are checked. Maybe get cell's category name and store it in an array.
Please advice how can I save all checked cells (ones with the "checked-image") on the "Apply" button click?
CheckBox class:
class CheckBox: UIButton {
let checkedImage = UIImage(named: "checked-image")! as UIImage
let uncheckedImage = UIImage(named: "unchecked-image")! as UIImage
var isChecked: Bool = true {
didSet {
if isChecked == true {
self.setImage(checkedImage, for: .normal)
} else {
self.setImage(uncheckedImage, for: .normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
self.isChecked = true
}
@objc func buttonClicked(sender: UIButton) {
if sender == self {
if isChecked == false {
isChecked = true
} else {
isChecked = false
}
}
}
}
TableView:
class FilterViewController: UIViewController {
var categories = [Category]()
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var applyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getCategories()
}
@IBAction func applyButtonClicked(_ sender: UIButton) {
print("Filter applied")
// save checked buttons
}
func getCategories() {
let url = URL(string: "https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.categories = try JSONDecoder().decode(Categories.self, from: data!).drinks
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}
extension FilterViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath) as! CategoryCell
cell.categoryLabel.text = categories[indexPath.row].strCategory
cell.styleButton()
return cell
}
}
My app:
Aucun commentaire:
Enregistrer un commentaire