How to programmatically select a row in UITableView in Swift

前端 未结 7 561
执笔经年
执笔经年 2020-12-24 04:52

I need to select a row in a UITableView programmatically using Swift 1.2.

This is the simple code:

var index = NSIndexPath(forRow: 0, inSection: 0)
         


        
相关标签:
7条回答
  • 2020-12-24 05:25

    Reusable function with validation of table size

    Swift 4 and 5

    This reusable function works and validate the size of table.

    func selectRow(tableView: UITableView, position: Int) {
        let sizeTable = tableView.numberOfRows(inSection: 0)
        guard position >= 0 && position < sizeTable else { return }
        let indexPath = IndexPath(row: position, section: 0)
        tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
    }
    

    you can use it in this way

    selectRow(tableView: myTableView, position: pos)
    

    or you can implement this extension:

    extension UITableView {
        func selectRow(row: Int, section: Int = 0) {
            let sizeTable = self.numberOfRows(inSection: section)
            guard row >= 0 && row < sizeTable else { return }
            let indexPath = IndexPath(row: row, section: section)
            self.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
        }
    }
    

    and you can use it in this way:

    mytableView.selectRow(row: pos, section: 0)
    

    or

    mytableView.selectRow(row: pos)
    
    0 讨论(0)
提交回复
热议问题