2017-07-18 93 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

謝謝...這將是非常有益的 –

相關問題