2014-10-08 2 views
3

я разместил ранее - о том, как остановить несколько ячеек от того, чтобы быть выбран в моем представлении таблицы - ответ был использовать tableView.AllowsMultipleSelections=falseTableView AllowsMultipleSelection - Тем не менее позволяет множественный выбор

Я пытался и терпеть неудачу с тех пор, по сути, он, похоже, не подчиняется этому правилу.

Мой желаемый выход должен быть выбран из одной ячейки и имеет зеленый галочку рядом с ним (это работает), если выбрана новая ячейка, старый тик удален и перемещен в новую текущую ячейку.

Я пробовал много подходов, а последнее - создать свой собственный путь указателя от последнего выбранного индекса - затем установите аксессуар в ноль и измените значение на false. Это также не работает. Пожалуйста, помогите мне с тем, что я могу сделать неправильно.

Благодаря

import UIKit 

class QuizViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ 

    var countries = ["Germany", "France", "England", "Poland", "Spain"]; 

    var selected = -1; 

    @IBOutlet var tableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.tableView.allowsMultipleSelection = false; 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 



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

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     println("indexpath \(indexPath.row)"); 
     let cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: indexPath) as UITableViewCell 

     cell.textLabel?.text = self.countries[indexPath.row]; 
     cell.textLabel?.textAlignment = NSTextAlignment.Center; 


     let countryImage = String(self.countries[indexPath.row]) + ".png"; 
     cell.imageView?.image = UIImage(named: countryImage); 

     let image: UIImageView = UIImageView(); 
     cell.accessoryView = image; 
     return cell; 
    } 


    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 

     var cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: indexPath) as UITableViewCell 

     cell.textLabel?.text = self.countries[indexPath.row]; 
     cell.textLabel?.textAlignment = NSTextAlignment.Center; 


     let countryImage = String(self.countries[indexPath.row]) + ".png"; 
     cell.imageView?.image = UIImage(named: countryImage); 


     let imageName = "tick.png"; 
     let image: UIImageView = UIImageView(image: UIImage(named: imageName)); 
     cell.accessoryView = image; 

     if(selected != -1){ 
      //lets remove the tick from the previously selected cell and set selected to false 

      var cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: NSIndexPath(forRow: selected, inSection: 0)) as UITableViewCell 

      cell.accessoryView = nil; 
      cell.selected = false; 
     } 

     selected = indexPath.row; 
    } 

} 

enter image description here

enter image description here

Попытка предлагаемого решения

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: indexPath) as UITableViewCell 

    cell.textLabel?.text = self.countries[indexPath.row]; 
    cell.textLabel?.textAlignment = NSTextAlignment.Center; 

    let countryImage = String(self.countries[indexPath.row]) + ".png"; 
    cell.imageView?.image = UIImage(named: countryImage); 


    if(cell.selected){ 
     println("cell was set to selected at \(indexPath.row)"); 
     let imageName = "tick.png"; 
     let image: UIImageView = UIImageView(image: UIImage(named: imageName)); 
     cell.accessoryView = image; 
    }else{ 
     println("cell was NOT set to selected at \(indexPath.row)"); 
     let image: UIImageView = UIImageView(); 
     cell.accessoryView = image; 
    } 

    return cell; 
} 


func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 


    var cell = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: indexPath) as UITableViewCell 
    cell.selected = true; 

    if(selected != -1){ 
     var previous = self.tableView.dequeueReusableCellWithIdentifier("CountryCell", forIndexPath: NSIndexPath(forRow: selected, inSection: 0)) as UITableViewCell 
     previous.selected = false; 
    } 
    selected = indexPath.row; 
    tableView.reloadData(); 
} 
+0

Вы установили делегата tableview для себя? – ytbryan

+0

Я перетащил табличный вид на контроллер контроллера желтой кнопки наверху - добавит изображение в исходное сообщение сейчас – Biscuit128

ответ

4

Не изменяйте ячейку в didSelectRowAtIndexPath. Установите страну как «выбранную», а предыдущую - «не выбрано», а затем перезагрузите данные таблицы. Используйте выбранное (или нет) состояние, чтобы обновить ячейку визуально при вызове cellForRowAtIndexPath.

+0

Привет - спасибо за ответ. Я добавил свою попытку в нижней части исходного сообщения, я все еще терпеть неудачу :( – Biscuit128

+2

Вы по-прежнему пытаетесь изменить ячейку в 'didSelectRowAtIndexPath'. Я хочу сказать, что данные поддержки должны знать, . Вместо того, чтобы иметь строку в 'self.countries', у вас будет какой-то объект« Страна », который знает свое имя и будет ли он выбран. –

+0

ah ok, что имеет смысл - я попробую это сейчас - спасибо – Biscuit128

Смежные вопросы