Get UIScrollView to scroll to the top

前端 未结 15 1868
眼角桃花
眼角桃花 2020-12-07 08:41

How do I make a UIScrollView scroll to the top?

15条回答
  •  [愿得一人]
    2020-12-07 09:40

    Scroll to top for UITableViewController, UICollectionViewController or any UIViewController having UIScrollView

    extension UIViewController {
    
      func scrollToTop(animated: Bool) {
        if let tv = self as? UITableViewController {
            tv.tableView.setContentOffset(CGPoint.zero, animated: animated)
        } else if let cv = self as? UICollectionViewController{
            cv.collectionView?.setContentOffset(CGPoint.zero, animated: animated)
        } else {
            for v in view.subviews {
                if let sv = v as? UIScrollView {
                    sv.setContentOffset(CGPoint.zero, animated: animated)
                }
            }
        }
      }
    }
    

提交回复
热议问题