问题
I have a tableview with a custom cell. Below image shows the view hierarchy of my tableview cell.
When adding rows to the tableview I'm hiding the 'check Image' imageview using below code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = true
return cell
}
and when a row is clicked I'm showing the imageview again. Below is the code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = false
}
But the problem is when I click a row nothing happens. system execute the cell.checkImage.isHidden = false
code line, but the imageview doesn't appear. It is still hidden. Could someone tell me what I'm doing wrong here?
回答1:
You can't track cell checked status in your cell itself; the cell object is just a view onto your data and cells will be reused when the table view scrolls.
I suggest using a Set<IndexPath>
. In your cellForRowAt
you can check the contents of the set in order to determine whether the checkmark should be hidden:
var checked = Set<IndexPath>()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = self.checked.contains(indexPath)
return cell
}
in your didSelectRowAt
you simply toggle the set membership and reload the row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.checked.contains(indexPath) {
self.checked.remove(indexPath)
} else {
self.checked.insert(indexPath)
}
tableView.reloadRows(at:[indexPath], with:.fade)
}
回答2:
You have to manage your array (datasource)! when you click your row, update your array for that index and reload your table view.
Example :
Your array should have some flag like isChecked
toggle it's value from true to false or vice-versa.
In your cellForRowAtIndexPath
check this flag and show or hide your image according to that flag!
回答3:
first be sure your
tableview.delegate = self
second thing in did select row at index use that code
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! AccountsTableViewCell
cell.checkImage.isHidden = false
}
来源:https://stackoverflow.com/questions/47048272/ios-show-hide-views-inside-a-tableview-cell