Storyboard scroll view with text boxes

2019-08-22 04:14发布

问题:

I am creating a view in a storyboard that has a bunch of text boxes with a button at the bottom. When I click in the text box the keyboard appears. This hides some of my text boxes. All text boxes live within the scrollview. Is there a way in storyboarding (if not then in code) to make the scrollview scroll properly amongst all the content when the keyboard appears?

Do I have to dynamically change the content size when the keyboard appears, or is there a way that I can set up the scroll view such that it automagically gets resized when the keyboard appears.

回答1:

I think I had the same problem as you, and what I did was to dynamically change the contenSize property of my scroll view when the keyboard appears or hides.

I subscribed for keyboard notifications in the ViewController class that manages my scrollview:

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

And then do the resizing in the target method:

- (void)keyboardWillShow:(NSNotification *)note{
    NSDictionary *userInfo = note.userInfo;
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey]      doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    //This is the value of the rect where the keyboard is drawn, and may come with height and width swapped
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:duration 
                          delay:0 
                        options:UIViewAnimationOptionBeginFromCurrentState | curve             
                     animations:^{
                          yourScrollableView.frame = ......
                     } 
                     completion:nil];

}

Of course the same applies to keyboard hiding.