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

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

    For me scrollRectToVisible() didn't work (see here), so I used setContentOffset() and calculated it myself, based on AMAN77's answer:

    extension UIScrollView {
    
        func scrollToView(view:UIView, animated: Bool) {
            if let superview = view.superview {
                let child = superview.convert(view.frame, to: self)
                let visible = CGRect(origin: contentOffset, size: visibleSize)
                let newOffsetY = child.minY < visible.minY ? child.minY : child.maxY > visible.maxY ? child.maxY - visible.height : nil
                if let y = newOffsetY {
                    setContentOffset(CGPoint(x:0, y: y), animated: animated)
                }
            }
        }
    
    }
    

    It is for a horizontal scroll view, but the same idea can be applied vertically too.

提交回复
热议问题