Auto scrolling to a cell with a specific value

后端 未结 4 1635
盖世英雄少女心
盖世英雄少女心 2020-12-14 09:06

I have a list of numbers in a table view like this.

\"enter

As you can see th

相关标签:
4条回答
  • 2020-12-14 09:32

    Swift 3.0

     let indexPath = NSIndexPath(forRow: 5, inSection: 0)
     tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    

    Swift 4.0

    let lastRowIndex = self.tblRequestStatus!.numberOfRows(inSection: 0) - 1
    let pathToLastRow = IndexPath.init(row: lastRowIndex, section: 0)
    tableView.scrollToRow(at: pathToLastRow, at: .none, animated: false)
    
    0 讨论(0)
  • 2020-12-14 09:36

    Do this to find the first element in the array that is equal to groupNoToScroll. Then, go to that row.

        var rowToGoTo:Int = 0 //Rather use the Swift find function.
        for x in items{
            if x == groupNoToScroll{
                break
            }
            rowToGoTo++
        }
    
        let lastRow = tableView.indexPathsForVisibleRows()?.last as NSIndexPath
        if indexPath.row == lastRow.row {
            if scrollToTime == true {
               let indexPath = NSIndexPath(row: rowToGoTo, section: 0)
               tblBusList.scrollToRow(at: indexPath as IndexPath, at: .top, animated: true)
            }
        }
    

    But I would recommend doing this in viewDidAppear.

    As Isuru pointed out rather use the find function.

    0 讨论(0)
  • 2020-12-14 09:47

    Swift 4:

    let indexPath = IndexPath(row: row, section: section)
    tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    

    (first, of course, you have to assign values to row and section based on which cell you want to scroll to)

    0 讨论(0)
  • 2020-12-14 09:52

    You can use find the index of the item(which will be its row), and then scroll to that index.
    find function returns the index of a particular element in the array.

    if let index = find(items, groupNoToScroll)
    {
        let indexPath = NSIndexPath(forRow: index, inSection: 0)
        tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true)
    }
    
    0 讨论(0)
提交回复
热议问题