开发者

Avoiding scrolling when switching among text fields

开发者 https://www.devze.com 2023-01-07 23:35 出处:网络
I have a view controller for a view with six UITextFields.Whenever the user selects a text开发者_开发技巧 field, I need to scroll things upwards.So the text fields all set the view controller as their

I have a view controller for a view with six UITextFields. Whenever the user selects a text开发者_开发技巧 field, I need to scroll things upwards. So the text fields all set the view controller as their respective delegates. When the delegate method fires, it then calls a scroll method to scroll things up (if the keyboard is appearing) or down (if it is disappearing). The scroll method looks like this:

- (void) scroll: (CGFloat) distanceUp {
    [UIView beginAnimations:@"Scroll" context:NULL];
      //move some stuff up by distanceUp, or down if distanceUp is negative.
    [UIView commitAnimations];
}

If the user selects a text field, enters a value, then hits the DONE button on the keyboard, this works fine.

The problem comes when the user switches directly from one textfield directly to another. In that case, what happens is that the view jumps downwards, then scrolls back up. Obviously I would prefer that it just remain in place. How do I make it do that?


As suggested by the commenter tonclon, what I did was use the UIKeyboard notifications instead of the text field delegates. In viewDidLoad, I have the following:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];

The keyboardWillShow/hide methods call the scrolling up/down.

I deregister in both viewDidUnload and dealloc. [And I'm not sure if both of these deregisterings are necessary.]

0

精彩评论

暂无评论...
验证码 换一张
取 消