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

前端 未结 11 1797
有刺的猬
有刺的猬 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:53

    I know this question has already been answered, but I thought I would share the code combination that I used from @Adeel and @Basil answer, as it seems to work perfectly for me on iOS 9.

    -(void)textFieldDidBeginEditing:(UITextField *)textField {
    
        // Scroll to the text field so that it is
        // not hidden by the keyboard during editing.
        [scroll setContentOffset:CGPointMake(0, (textField.superview.frame.origin.y + (textField.frame.origin.y))) animated:YES];
    }
    
    -(void)textFieldDidEndEditing:(UITextField *)textField {
    
        // Remove any content offset from the scroll
        // view otherwise the scroll view will look odd.
        [scroll setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    

    I also used the animated method, it makes for a much smoother transition.

提交回复
热议问题