Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

后端 未结 11 1626
遇见更好的自我
遇见更好的自我 2020-12-29 03:35

I have a few screens worth of content within my UIScrollView which only scrolls vertically.

I want to programmatically scroll to a view contained somewhere in it\'s

11条回答
  •  滥情空心
    2020-12-29 03:49

    You can use the following method , it works well for me

    func scrollViewToTop( _ someView:UIView)
    {
    
        let targetViewTop = someView.frame.origin.y
        //If you have a complicated hierarchy it is better to 
        // use someView superview (someView.superview?.frame.origin.y) and figure out your view origin
        let viewToTop = targetViewTop - scrollView.contentInset.top
        scrollView.setContentOffset(CGPoint(x: 0, y: viewToTop), animated: true)
    
    }
    

    Or you can have as an extension

     extension UIScrollView
    {
           func scrollViewToTop( _ someView:UIView){
        let targetViewTop = someView.frame.origin.y
        let viewToTop = targetViewTop - self.contentInset.top
        self.setContentOffset(CGPoint(x: 0, y: viewToTop), animated: true)
    
       }
    }
    

    here are constraints for the scroll view

    some screen shots

    Screen Shots2

提交回复
热议问题