user5184878
user5184878

Reputation: 101

How to select a UITableview Cell automatically?

I'm working on a Quiz App. I am getting questions from API. I'm using tableview for the Options.

Now when the user selects the answer for the 1st question & presses Next comes to the previous question. Then the selected answer has to remain selected.

I researched a lot and found this:

Programmatically emulate the selection in UITableViewController in Swift

But I can't automatically select the user selected answer in my table view.

This is my 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. I have over 20 Questions. So i have to save the Selected answer for Each Questions separately.

  2. I can't select the answer using the indexpath position because the options will change it positions randomly when it is accessed for the second time.

Upvotes: 0

Views: 166

Answers (1)

iRiziya
iRiziya

Reputation: 3245

You can do it this way : When you press next, store the selected answer's index into a variable and when you come back to previous, check that index in willDisplayCell method and the set your cell selected.

Take a variable in your controller

var selectedAnsIndexPath:NSIndexPath?

your next button action will be something like

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

and then

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

Try this, it may work for you!

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) 
} 
}

Upvotes: 1

Related Questions