Select First Row as default in UITableView

后端 未结 11 1738
悲哀的现实
悲哀的现实 2021-01-30 20:12

I have an application that is viewbased and I am adding a tableview as a subview to the main view. I have taken UITableViewDelegate to respond the table methods.

11条回答
  •  借酒劲吻你
    2021-01-30 20:41

    Here is my solution for swift 3.0:

    var selectedDefaultIndexPath = false
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        if dataSource.isEmpty == false, selectedDefaultIndexPath == false {
            let indexPath = IndexPath(row: 0, section: 0)
            // if have not this, cell.backgroundView will nil.
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
            // trigger delegate to do something.
            _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
            selectedDefaultIndexPath = true
        }
    }
    
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        let cell = tableView.cellForRow(at: indexPath)
        cell?.selectedBackgroundView?.backgroundColor = UIColor(hexString: "#F0F0F0")
    
        return indexPath
    }
    

提交回复
热议问题