Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

ios - Selecting TableView Cell Activates Checkmark in Rows in Multiple Sections

I've implemented checkmarks (when row is selected) with the following code in cellForRowAt:

// Add a checkmark to row when selected
    if selectedIngredients.contains(indexPath.row) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }

However, when I select a row, that index.row from each section gets the checkmark: enter image description here

This seems like it could be because I'm only specifying the indexPath.row, but not the section. How can I code this so that only the selected row within the section I selected gets the checkmark?

question from:https://stackoverflow.com/questions/65901113/selecting-tableview-cell-activates-checkmark-in-rows-in-multiple-sections

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use data store for save checkmarks like this:

var selectedIngredients: Set<IndexPath> = [] // use set for unique save

then didSelect callBack:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if self.selectedIngredients.contains(indexPath) {
            self.selectedIngredients.remove(indexPath)
            
        } else {
            self.selectedIngredients.insert(indexPath)
        }
        
        self.tableView.reloadData()
    }

after reload in CellForRow:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if selectedIngredients.contains(indexPath) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }
}

If you want it to have only one Row contain checkmark:

var selectedIngredients: IndexPath? = nil

and didSelect CallBack:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
            self.selectedIngredients = indexPath
        }

and finally:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if selectedIngredients == indexPath {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...