cdub
cdub

Reputation: 25701

How to keep a UITableView cell selected

I have the following code but when I select my cell it doesn't stay selected:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath);
    // cell.delegate = self;

    cell.backgroundColor = UIColor.clear;

    let select = UIView();
    select.backgroundColor = UIColor.green;
    cell.selectedBackgroundView = select;

    cell.textLabel?.text = activities[indexPath.row];

    // cell.selectionStyle = .blue;

    return cell;
}

How do I keep the cell selected? It removes the selection when I let my touch leave the cell.

Upvotes: 1

Views: 1868

Answers (2)

Rashed
Rashed

Reputation: 2425

Here is my solution. This might help you.

func tableView(........) {
    if cell.selected {
        cell.selected = true
    //  cell.backgroundColor = UIColor.blackColor()
    } else {
        cell.selected = false
    //  cell.backgroundColor = UIColor.blackColor()
    }
}

Upvotes: -1

Hitesh Agarwal
Hitesh Agarwal

Reputation: 2005

Create a int variable which store selected cell index. In didselctedIndexPath set it's value. check it's value in cellforrowatindexpath .

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var array = ["One", "Two", "Three", "Four", "Five"]
    var selectedIndex:Int? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()

        tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell
        cell.lblTitle.text = array[indexPath.row]

        if let index = selectedIndex, indexPath.row == index {
            cell.backgroundColor = UIColor.blue
        }

        let cellBackground = UIView()
        cellBackground.backgroundColor = UIColor.blue
        cell.selectedBackgroundView = cellBackground
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
    }
}

Upvotes: 2

Related Questions