applejuiceteaching
applejuiceteaching

Reputation: 1493

Set UITableViewCell as selected in code

I feel this is a stupid question but I can not get it to work. I want the cell that has a title to match a certain string. If this cell matches that string, I want the cell to be highlighted. However, when I run my app the cell is selected (highlighted in grey like a regular table view) for a split second and then disappears. This is my attempt at doing so.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("RouteCell") as! UITableViewCell

var singleStop = self.stops[indexPath.row]

if(singleStop.stop_name == routeLabelName) // string comparison
{
    cell.highlighted = true
    cell.selected = true

}

cell.textLabel!.text = singleStop.stop_name

cell.imageView!.image = UIImage(named: "ArrowPathMiddle.png")

return cell
}

Upvotes: 0

Views: 290

Answers (1)

Doro
Doro

Reputation: 2413

Set multipleselection on your view didload

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

next rewrite your code as

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("RouteCell") as! UITableViewCell

var singleStop = self.stops[indexPath.row]


if (singleStop.stop_name == routeLabelName)
    {
        self.tableView .selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
    }
    else
    {
       self.tableView .deselectRowAtIndexPath(indexPath, animated: false)
    }

cell.textLabel!.text = singleStop.stop_name

cell.imageView!.image = UIImage(named: "ArrowPathMiddle.png")

return cell
}

Upvotes: 1

Related Questions