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

后端 未结 11 1623
遇见更好的自我
遇见更好的自我 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:57

    swift 5.0 code

    extension UIScrollView {
    
        // Scroll to a specific view so that it's top is at the top our scrollview
        func scrollToView(view:UIView, animated: Bool) {
            if let origin = view.superview {
                // Get the Y position of your child view
                let childStartPoint = origin.convert(view.frame.origin, to: self)
                // Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview
                self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y,width: 1,height: self.frame.height), animated: animated)
            }
        }
    
        // Bonus: Scroll to top
        func scrollToTop(animated: Bool) {
            let topOffset = CGPoint(x: 0, y: -contentInset.top)
            setContentOffset(topOffset, animated: animated)
        }
    
        // Bonus: Scroll to bottom
        func scrollToBottom() {
            let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
            if(bottomOffset.y > 0) {
                setContentOffset(bottomOffset, animated: true)
            }
        }
    
    }
    

提交回复
热议问题