如何创建一个完全适合键盘的UITextView?

Sam*_*erg 5 iphone cocoa-touch ios ios5

我想创建一个视图,例如Facebook或Twitter应用程序的共享对话框,例如,只有UITextView和永久键盘.我可以看到如何从这个答案可见的键盘开始,但我不知道如何调整UITextView的大小恰好适合键盘上方.如果我不这样做,文字可以隐藏在键盘下面,这是很尴尬的.

Sam*_*erg 3

我在Apple文档中找到了一个有用的代码示例:https://developer.apple.com/library/ios/#samplecode/KeyboardAccessory/Introduction/Intro.html

这是我最终得到的代码。我不担心键盘隐藏,因为在我看来,键盘永远不应该隐藏。

- (void)viewWillAppear:(BOOL)flag
{
    [super viewWillAppear:flag];

    // Listen for the keyboard to show up so we can get its height
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    // Set focus on the text view to display the keyboard immediately
    [self.textView becomeFirstResponder];
}
- (void)keyboardWillShow:(NSNotification *)notification
{
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     */

    NSDictionary *userInfo = [notification userInfo];

    // Get the origin of the keyboard when it's displayed.
    NSValue* keyboardFrame = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Get the top of the keyboard as the y coordinate of its origin in self's view's
    // coordinate system. The bottom of the text view's frame should align with the
    // top of the keyboard's final position.
    CGRect keyboardRect = [keyboardFrame CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

    // Set the text view's frame height as the distance from the top of the view bounds
    // to the top of the keyboard
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    self.textView.frame = newTextViewFrame;
}
Run Code Online (Sandbox Code Playgroud)