UITableView - scroll to the top

前端 未结 30 3011
南方客
南方客 2020-11-28 17:22

In my table view I have to scroll to the top. But I cannot guarantee that the first object is going to be section 0, row 0. May be that my table view will start from section

30条回答
  •  庸人自扰
    2020-11-28 17:52

    I use tabBarController and i have a few section in my tableview at every tab, so this is best solution for me.

    extension UITableView {
    
        func scrollToTop(){
    
            for index in 0...numberOfSections - 1 {
                if numberOfSections > 0 && numberOfRows(inSection: index) > 0 {
                    scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true)
                    break
                }
    
                if index == numberOfSections - 1 {
                    setContentOffset(.zero, animated: true)
                    break
                }
            }
    
        }
    
    }
    

提交回复
热议问题