2017-07-18 90 views
-1

是否可以一次只选择两个UITableview单元格?目前我只能设置单个选择或UITableView的多个选择。如何在swift中一次只选择两个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 
    } 

回答

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 
    } 
+0

如何做到这一点? –

+0

我会更新答案更详细 –

+0

谢谢...这将是非常有益的 –

相关问题