Programmatically scroll a UIScrollView

前端 未结 9 1165
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 15:52

I have a UIScrollView which has several views. When a user flicks their finger, the view scrolls to the right or left depending on the direction of the finger f

9条回答
  •  心在旅途
    2020-11-29 16:12

    I'm amazed that this topic is 9 years old and the actual straightforward answer is not here!

    What you're looking for is scrollRectToVisible(_:animated:).

    Example:

    extension SignUpView: UITextFieldDelegate {
        func textFieldDidBeginEditing(_ textField: UITextField) {
            scrollView.scrollRectToVisible(textField.frame, animated: true)
        }
    }
    

    What it does is exactly what you need, and it's far better than hacky contentOffset

    This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

    From: https://developer.apple.com/documentation/uikit/uiscrollview/1619439-scrollrecttovisible

提交回复
热议问题