Richard Topchii
Richard Topchii

Reputation: 8165

UITableViewController doesn't select a cell on initialization

I have the following subclass of UITableViewController:

final public class ILoveAppleSelectorTableViewController: UITableViewController {
    public weak var delegate: ILoveAppleSelectorTableViewControllerDelegate?
    public var data = [ILoveAppleGroupModel]()

    convenience init() {
        self.init(style: .plain)
    }

    convenience init(data: [ILoveAppleGroupModel]) {
        self.init(style: .plain)
        self.data = data
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        title = "Select APple Product"
        tableView.registerCellClass(CheckmarkTableViewCell.self)
        tableView.allowsSelection = true
        tableView.allowsMultipleSelection = false
    }

    // MARK: - Selection

    public func selectItem(at indexPath: IndexPath) {
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
    }

    // MARK: - Table view data source

    override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CheckmarkTableViewCell = tableView.dequeueCell(for: indexPath)
        let item = data[indexPath.row]
        cell.textLabel?.text = item.material_group_name
        return cell
    }

    override public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedappleProduct = data[indexPath.row]
        delegate?.ILoveAppleSelector(controller: self, didSelect: selectedappleProduct)
    }
}

I create an instance of it and call selectItem method:

let data = Array(appleProducts)
let selector = AppleProductSelector(data: data)
selector.selectItem(at: IndexPath(indexes: [0, 0]))
navigationController?.pushViewController(selector, animated: true)

I check in the debugger that selectItem method gets successfully called, however nothing gets selected.

If I select an item on viewWillAppear instead, everything works as expected and the item is being shown as selected:

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    selectItem(at: selectedIndexPath)
}

Upvotes: 0

Views: 50

Answers (1)

DonMag
DonMag

Reputation: 77477

By default, a table view controller will clear the selection when the table view is shown.

You are instantiating your class, then "selecting" a row, then pushing the VC onto the stack. When it appears, it then clears the selection.

In IB / Storyboard, it's controlled by a checkbox:

enter image description here

(un-check the box to prevent selection clearing)

In code, you can add this in your init func (or perhaps in viewDidLoad()):

self.clearsSelectionOnViewWillAppear = false

Upvotes: 2

Related Questions