2015-09-10 4 views
0

Я работаю над викториной. Я получаю вопросы от API. Я использую tableview для параметров.Как автоматически выбрать ячейку UITableview?

Теперь, когда пользователь выбирает ответ для 1-го вопроса & прессов Далее идет предыдущий вопрос. Затем выбранный ответ должен оставаться выбранным.

Я исследовал много и нашел это:

Programmatically emulate the selection in UITableViewController in Swift

Но я не могу автоматически выбрать пользователя выбранного ответа на мой взгляд таблицы.

Это мой Present UI

VC

func getOptions(){ 
    OptionArray.removeAll(keepCapacity: false) 
    Alamofire.request(.GET, "http://www.wins.com/index.php/capp/get_chapter_answers/\(EID)/\(QuestionID[Qindex])") 
     .responseJSON { (_, _, data, _) in 
      println(data) 
      let json = JSON(data!) 
      let catCount = json.count 
      for index in 0...catCount-1 { 
       let disp = json[index]["DISPLAY_STATUS"].string 
       if disp == "Y"{ 
       let op = json[index]["ANSWER"].string 
       self.OptionArray.append(op!) 
       let ans = json[index]["RIGHT_ANSWER"].string 
       self.AnswerArray.append(ans!) 
       } 
      } 
      self.OptionTable.reloadData() 
      println(self.OptionArray.count) 
    } 
} 

@IBAction func Previous(sender: AnyObject) { 
    Qindex-- 
    ShowQuestion() 
} 


@IBAction func Next(sender: AnyObject) { 
    Qindex++ 
    ShowQuestion() 
    } 


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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return self.OptionArray.count 
} 


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

    let cell = self.OptionTable.dequeueReusableCellWithIdentifier("Option") as! OptionCell 

    cell.Optionlabel?.text = self.OptionArray[indexPath.row] 
    cell.layer.masksToBounds = true; 
    cell.layer.cornerRadius = 6; 
    cell.layer.borderWidth = 2.0 
    cell.layer.borderColor = colorsArray[1].CGColor 
    return cell 

} 

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

    let indexPath = tableView.indexPathForSelectedRow(); 

    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! OptionCell; 

    if currentCell.selected == true{ 
     currentCell.layer.borderWidth = 4.0 
     currentCell.layer.borderColor = colorsArray[6].CGColor 
     println(currentCell.Optionlabel?.text) 
    } 
} 

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 


    let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! OptionCell; 

    if currentCell.selected == false{ 
     currentCell.layer.borderWidth = 2.0 
     currentCell.layer.borderColor = colorsArray[1].CGColor 

    } 
} 

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    return 70 
} 

UPDATE

  1. У меня есть более 20 вопросов. Поэтому я должен сохранить выбранный ответ для каждого вопроса отдельно.

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

ответ

1

Вы можете сделать это следующим образом: При нажатии next, хранить индекс выбранного ответа в переменную и, когда вы вернетесь к previous, проверить, что индекс в willDisplayCell метода и установленного вашей выделенной ячейки.

Возьмите переменную в контроллере

var selectedAnsIndexPath:NSIndexPath? 

ваша следующая кнопка действия будет что-то вроде

@IBAction func Next(sender: AnyObject) { 
    self.selectedAnsIndexPath = tableView.indexPathForSelectedRow() 
    Qindex++ 
    ShowQuestion() 
} 

, а затем

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
    if(indexPath == self.selectedAnsIndexPath) 
    { 
     cell.setSelected(true, animated: false) 
    } 
} 

Попробуйте это, он может работать для вас!

UPDATE

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

let cell = self.OptionTable.dequeueReusableCellWithIdentifier("Option") as! OptionCell 

cell.Optionlabel?.text = self.OptionArray[indexPath.row] 
cell.QueID = QuestionID[Qindex] 
cell.layer.masksToBounds = true; 
cell.layer.cornerRadius = 6; 
cell.layer.borderWidth = 2.0 
cell.layer.borderColor = colorsArray[1].CGColor 


if let val = examDic[cell.QueID] 
{ 
    if self.OptionArray[indexPath.row] == val 
    { 
     selectedAnsIndexPath = indexPath 
     cell.setSelected(true, animated: true) 
     cell.layer.borderWidth = 4.0 
     cell.layer.borderColor = colorsArray[6].CGColor 
    } 
} 

return cell 

} 

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

if selectedAnsIndexPath != nil{ 
    OptionTable.deselectRowAtIndexPath(selectedAnsIndexPath!, animated: false) 
    self.tableView(OptionTable, didDeselectRowAtIndexPath: selectedAnsIndexPath!) 
    println(selectedAnsIndexPath!.row) 
} 

let indexPath = OptionTable.indexPathForSelectedRow(); 
let currentCell = OptionTable.cellForRowAtIndexPath(indexPath!) as! OptionCell; 

if currentCell.selected == true{ 
    currentCell.layer.borderWidth = 4.0 
    currentCell.layer.borderColor = colorsArray[6].CGColor 
    var sqid = QuestionID[Qindex] 
    var sanswer = currentCell.Optionlabel!.text 
    examDic[sqid] = sanswer! 
    println(examDic) 
} 
} 
+0

Он не выбирает вариант и смотрите обновление также пример проекта – user5184878

+0

загрузки, если это возможно – iRiziya

+0

К сожалению, это большой проект ... – user5184878

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