简体   繁体   中英

Deselect row in tableview after programmatically selecting

I followed this thread first: How to programmatically select a row in UITableView in Swift 1.2 (Xcode 6.4)

Which did help for the selection, but when I tap the screen to select another row, the previously (programmatically) set row will not trigger the deselect message. The cells that are selected naturally (by tapping the screen), do receive the deselect message.

I need that row that is programmatically selected to receive the deselect message (non-programmatically).

(I'm working in a UITableView subclass - so it's not a delegate, it's overrides).

Example Video

My code:

        if let selectedRow = viewModel.selectedRow {
        defaultSelectedPath = IndexPath(row: selectedRow, section: 0)
        if let defaultSelectedPath = defaultSelectedPath {
            let selectedCell = self.tableView.cellForRow(at: defaultSelectedPath)
            self.tableView.selectRow(at: defaultSelectedPath, animated: true, scrollPosition: .none)
            self.tableView(self.tableView, didSelectRowAt: defaultSelectedPath)

            selectedCell?.accessoryType = .checkmark
        }
    }

Hack Fix:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var cell = tableView.cellForRow(at: indexPath)
    cell?.accessoryType = .checkmark

    if let defaultSelectedPath = self.defaultSelectedPath {
        if indexPath != defaultSelectedPath {
            cell = tableView.cellForRow(at: defaultSelectedPath)
            tableView.deselectRow(at: defaultSelectedPath, animated: false)
            self.tableView(self.tableView, didDeselectRowAt: defaultSelectedPath)
            cell?.accessoryType = .none
        }
        self.defaultSelectedPath = nil
    }
}

Please tell me there's a better way to do this.

you can use :-

self.clearsSelectionOnViewWillAppear = true

on viewDidLoad()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM