#5 Question1 How to change image for cell?

Stephen Huang
4 min readMay 9, 2021

--

最近在做tableViewController練習
希望能做一個待辦事項清單

在製作cell內容,希望能在完成的事項上打勾
未完成則沒打勾

嘗試了很久一直做不出來
於是參考學長的文章

做簡單的Button + image以及一個Label

寫好後產生一個現象
不管點哪個cell
只有第0個cell會一直打勾跟取消,其他的cell卻不變

作法如下

在自訂 ”LTableViewCell” 頁面新增一個protocol


protocol CheckBox {
func checkBox(state: Bool, index: Int?)
}

定義class

class doingList {
var title = ""
var checked = false

convenience init(title: String) {
self.init()
self.title = title
}
}

title顯示在cell的Label,Bool控制image的打勾跟沒打勾

@IBAction func checkButton(_ sender: Any) {

if doingLists![indexP!].checked {

delegate?.checkBox(state: false, index: indexP)
} else {
delegate?.checkBox(state: true, index: indexP)
}
}

主頁面LoveTableViewController匯入CheckBox protocol
並定義func checkBox的動作

import UIKitclass LoveTableViewController: UITableViewController, CheckBox {func checkBox(state: Bool, index: Int?) {        doingLists[index!].checked = state
tableView.reloadRows(at: [IndexPath(row: index!, section: 0)], with: UITableView.RowAnimation.none)

}

cell顯示的內容

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoveCell", for: indexPath) as! LTableViewCell
cell.titleLabel.text = doingLists[indexPath.row].title

cell.delegate = self
cell.doingLists = doingLists
cell.indexP = indexPath.row

if doingLists[indexPath.row].checked {
cell.imageButton.setImage(UIImage(systemName: "checkmark.square"), for: UIControl.State.normal)
} else {
cell.imageButton.setImage(UIImage(systemName: "square"), for: .normal)
}

return cell
}

請問有沒有好心人可以協助解答,大大的感謝。

--

--

Stephen Huang
Stephen Huang

Written by Stephen Huang

Wish me luck on the way become iOS app developer!

No responses yet