How to make a UIScrollView auto scroll when a UITextField becomes a first responder

前端 未结 11 1790
有刺的猬
有刺的猬 2021-01-31 03:24

I\'ve seen posts around here that suggest that UIScrollViews should automatically scroll if a subview UITextField becomes the first responder; however,

11条回答
  •  时光说笑
    2021-01-31 03:40

    Here is the Swift 4 update to @Supertecnoboff's answer. It worked great for me.

    func textFieldDidBeginEditing(_ textField: UITextField) {
        scroll.setContentOffset(CGPoint(x: 0, y: (textField.superview?.frame.origin.y)!), animated: true)
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        scroll.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    }
    

    Make sure to extend UITextFieldDelegate and set the textfields' delegate to self.

提交回复
热议问题