How to make a UIScrollView auto scroll when a UITe

2019-03-09 08:47发布

I've seen posts around here that suggest that UIScrollViews should automatically scroll if a subview UITextField becomes the first responder; however, I can't figure out how to get this to work.

What I have is a UIViewController that has a UIScrollView and within the UIScrollView there are multiple textfields.

I know how to do this manually if necessary; however, from what I've been reading, it seems possible to have it autoscroll. Help please.

8条回答
Explosion°爆炸
2楼-- · 2019-03-09 09:33

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-03-09 09:35

You can use this function for autoScroll of UITextField

on UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {

[self autoScrolTextField:textField onScrollView:self.scrollView];
}




- (void) autoScrolTextField: (UITextField *) textField onScrollView: (UIScrollView *) scrollView { 
 float slidePoint = 0.0f;
float keyBoard_Y_Origin = self.view.bounds.size.height - 216.0f;
float textFieldButtomPoint = textField.superview.frame.origin.y + (textField.frame.origin.y + textField.frame.size.height);

if (keyBoard_Y_Origin < textFieldButtomPoint - scrollView.contentOffset.y) {
    slidePoint = textFieldButtomPoint - keyBoard_Y_Origin + 10.0f;
    CGPoint point = CGPointMake(0.0f, slidePoint);
    scrollView.contentOffset = point;
}

EDIT:

Im now using IQKeyboardManager Kudos to the developer of this, you need to try this.

查看更多
登录 后发表回答