[英]How to show check mark when cell is checked
我在tableview中有3个table view单元格。 我想在选中时在单元格上显示选中标记。
这是我的代码:
import UIKit
class UserRightRoleTableViewController: UITableViewController {
@IBOutlet var roleTableView: UITableView!
@IBOutlet var managerTableViewCell: UITableViewCell!
@IBOutlet var readerTableViewCell: UITableViewCell!
@IBOutlet var memberTableViewCell: UITableViewCell!
var checked = [false, false, false]
var cells = [UITableViewCell]()
var roleString = ["Manager, Member, Reader"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Role"
navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
let backButton = UIBarButtonItem(title: "<User", style: UIBarButtonItemStyle.Done, target: self, action: "backToVC")
navigationItem.leftBarButtonItem = backButton
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
cells = [managerTableViewCell, memberTableViewCell, readerTableViewCell]
}
func backToVC() {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func backToUserRightTableViewControllerAction(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
checked[0] == true ? (managerTableViewCell.accessoryType = .Checkmark) : (managerTableViewCell.accessoryType = .None)
} else if indexPath.row == 1 {
checked[1] == true ? (memberTableViewCell.accessoryType = .Checkmark) : (memberTableViewCell.accessoryType = .None)
} else {
checked[2] == true ? (readerTableViewCell.accessoryType = .Checkmark) : (readerTableViewCell.accessoryType = .None)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
checked[indexPath.row] = true
}
}
但这是行不通的。
您需要更新细胞的accessoryType
在didSelectRowAtIndexPath
的功能,除了更新checked
。
您的willDisplayCell
函数可以变得更加简单:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.accessoryType = checked[indexPath.row] ? .Checkmark : .None
}
谢谢@rmaddy,我已经通过以下方法解决了问题:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.accessoryType = checked[indexPath.row] ? .Checkmark : .None
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
checked[0] = false
checked[1] = false
checked[2] = false
checked[indexPath.row] = true
roleTableView.reloadData()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.