如何在iOS 5中显示由键盘隐藏的UI元素?

时间:2011-10-21 07:22:26

标签: ios5 uielement keypad

在iOS 5中,iPad支持3种不同的键盘(正常,分割,上移)。以前当键盘出现时,控制器将通过KeyboardDidShowNotification通知。在这里,如果我们有任何按键盘隐藏的UI元素将设置偏移量并向上推动元素(使用滚动视图)。在iOS 5中,我们必须根据键盘的类型进行处理。我们如何了解键盘类型。我们可以为新的键盘类型做些什么?。

谢谢, durai。

2 个答案:

答案 0 :(得分:0)

如果您对UIKeyboardWillShowNotificationUIKeyboardWillHideNotification作出反应,那么您应该没问题,因为只有当键盘以“正常模式”显示时才会发送...如果用户将其拉起或拆分,您将收到UIKeyboardWillHideNotification(奇怪的行为,但苹果唯一的选择是使其向后兼容iOS 4应用程序)

答案 1 :(得分:0)

如果要在键盘下方自动滚动隐藏的textView或textField元素,请单击编辑文本元素,以下代码将帮助您完成ios5:

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, _activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:_activeField.frame animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    _activeField = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    [self registerForKeyboardNotifications];
}