键盘在键入时阻止屏幕

时间:2013-04-11 02:17:03

标签: iphone ios objective-c uitextview

我正在创建一个包含多个UITextFieldUITextView的应用 UITextView位于屏幕底部,每当键入开始时,键盘会阻止UITextView

当键盘出现在屏幕上时,如何向上移动表单视图?键盘消失后再将其向下移动?

3 个答案:

答案 0 :(得分:1)

最好的答案是尽量避免这样做。

但是,如果你把你的东西放在UIScrollView或UITableView中,你可以在它成为第一响应者时滚动到输入。

答案 1 :(得分:0)

我喜欢用这个:https://github.com/michaeltyson/TPKeyboardAvoiding 它对我来说非常好用,并且易于使用。

答案 2 :(得分:0)

确保在类中实现UITextFieldDelegate。这些委托方法应该为名为activeField的文本字段提供技巧:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [activeField setDelegate:self];    
    [self configureView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return TRUE;
}

// 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 application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeField.frame.origin.y-kbSize.height);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

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

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

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