是否有可能一次只能选择UITableview的两个单元格?目前我只能设置UITableView的单选或多选。
请允许任何人在Swift3中发布这个想法或代码吗?
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
let currentItem = data[indexPath.row]
if currentItem.selected {
cell.imageView!.image = UIImage(named:"check")!
cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
} else {
cell.imageView!.image = nil
cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
}
return cell
}
答案 0 :(得分:1)
选择单元格后,您将在didSelectRowAtIndex
中获得回调。因此,您可以跟踪所选单元格并相应地取消选择单元格。使用数组来跟踪所有选定的单元格
var selectedIndexes = [Int]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (selectedIndexes.contains(indexPath.row)) {
selectedIndexes.remove(at: selectedIndexes.index(of: indexPath.row)!)
} else {
if selectedIndexes.count == 2 {
selectedIndexes[0] = indexPath.row
} else {
selectedIndexes.append(indexPath.row)
}
}
tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyIdentifier") as! UITableViewCell
let currentItem = data[indexPath.row]
if selectedIndexes.contains(indexPath.row) {
cell.imageView!.image = UIImage(named:"check")!
cell.textLabel!.font = UIFont(name:"OpenSans-Bold", size:15)
} else {
cell.imageView!.image = nil
cell.textLabel!.font = UIFont(name:"OpenSans-Regular", size:15)
}
return cell
}