Учитывая, что вы хотите сохранить только один выбор, и если у вас есть пользовательский UITableViewCell
, я бы порекомендовал следующее.
В вашем UITableViewController
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//...
let data = dataArray[indexPath.row]
if data.isSelected {
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
//...
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let data = dataArray[indexPath.row]
data.isSelected = true
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.setSelected(true, animated: true)
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let data = dataArray[indexPath.row]
data.isSelected = false
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.setSelected(false, animated: true)
}
На заказ UITableViewCell
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
self.accessoryType = .None
if selected {
self.accessoryType = .Checkmark
}
}
Пока allowsMultipleSelection
не включен, он автоматически обрабатывает отмену выбора других ячеек, когда выбирается новая. Если allowMultipleSelection
включен, то он также будет работать, за исключением того, что вам просто нужно снова нажать, чтобы отменить выбор.