2016-05-03 10 views
0

Я использую swift 2 и UITableViews, и когда я нажимаю на ячейку, появляется галочка, но я не хочу, чтобы в моей таблице можно было проверить только одну ячейку, чтобы другой галочки исчезнут из моего стола. Я пробовал разные техники без успеха. У меня есть CustomCell с ярлыком.Не удается проверить всю ячейку перед проверкой одного swift 2

Вот мой код:

import UIKit 


class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ 
    @IBOutlet weak var tableView: UITableView! 

    var answersList: [String] = ["One","Two","Three","Four","Five"] 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return answersList.count 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomCell", forIndexPath: indexPath) as! MyCustomCell 
     cell.displayAnswers(answersList[indexPath.row]) // My cell is just a label  
     return cell 
    } 

    // Mark: Table View Delegate 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     // Element selected in one of the array list 
     tableView.deselectRowAtIndexPath(indexPath, animated: true) 

     if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
      if cell.accessoryType == .Checkmark { 
       cell.accessoryType = .None 
      } else { 
       cell.accessoryType = .Checkmark 
      } 
     } 
    } 

} 

ответ

5

Предполагая, что вы только раздел здесь, что вы можете сделать

// checkmarks when tapped 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let section = indexPath.section 
    let numberOfRows = tableView.numberOfRowsInSection(section) 
    for row in 0..<numberOfRows { 
     if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) { 
      cell.accessoryType = row == indexPath.row ? .Checkmark : .None 
     } 
    } 
} 
+0

Большое спасибо ! Он отлично работает – fandro

0

Фиксированный код из @SirH работать с Swift 3

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    tableView.deselectRow(at: indexPath, animated: true) 



    let section = indexPath.section 
    let numberOfRows = tableView.numberOfRows(inSection: section) 
    for row in 0..<numberOfRows { 
     if let cell = tableView.cellForRow(at:IndexPath(row: row, section: section)) { 
      cell.accessoryType = row == indexPath.row ? .checkmark : .none 
     } 
    } 
}