Как мне создать UITextView, который точно подходит над клавиатурой? - PullRequest
5 голосов
/ 18 февраля 2012

Я хочу создать представление, например, диалоговое окно обмена приложениями Facebook или Twitter, например, где есть только UITextView и постоянная клавиатура.Я могу видеть, как начать с клавиатуры, видимой из этого ответа , но я не уверен, как изменить размер UITextView, чтобы он помещался точно над клавиатурой.Если я этого не сделаю, текст может быть скрыт под клавиатурой, что неудобно.

Ответы [ 5 ]

3 голосов
/ 21 февраля 2012

Я нашел полезный пример кода в документации 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;
}
3 голосов
/ 18 февраля 2012

Вы можете подписаться на UIKeyboardWillShowNotification.Уведомление включает в себя рамку клавиатуры, так что вы можете изменить размер изображения, чтобы оно соответствовало оставшемуся месту.

2 голосов
/ 18 февраля 2012

Вы можете получить размер клавиатуры следующим образом:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardIsUp:) name:UIKeyboardDidShowNotification object:nil];

- (void)keyboardIsUp:(NSNotification *)notification{

    CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size;
    NSLog(@"%f", keyboardSize.height);
}

[РЕДАКТИРОВАТЬ] Режим ландшафта

Я попробовал его на симуляторе iPas, и он вернул 264 вкнижный режим для QWERTY-клавиатуры, но когда вы запускаете приложение или поворачиваете в альбомный режим, он возвращает 1024. Поэтому вам может потребоваться запросить ширину вместо высоты в альбомном режиме ...

[РЕДАКТИРОВАТЬ]

Благодаря комментарию Роба Майоффа больше нет проблем с альбомным режимом

[РЕДАКТИРОВАТЬ]

Это нелучший способ сделать это, но это дает представление.Я посмотрю на это позже

- (void)viewDidLoad
{
    [super viewDidLoad];

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

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

    CGSize size = [self.view convertRect:self.view.frame toView:nil].size;
    CGFloat width =  size.width;
    CGFloat height = 40;
    CGFloat x =  0;
    CGFloat y =  size.height+40;

    aboveKBView = [[[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)] autorelease];
    [aboveKBView setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:aboveKBView];
}

- (void)keyboardWillHide:(NSNotification *)notification{
    [aboveKBView setHidden:YES];
}

- (void)keyboardWillShow:(NSNotification *)notification{
    NSLog(@"keyboardIsUp");

    CGSize keyboardSize = [self.view convertRect:[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil].size;

    CGSize size = [self.view convertRect:self.view.frame toView:nil].size;
    CGFloat width =  size.width;
    CGFloat height = 40;
    CGFloat x =  0;
    CGFloat y =  size.height-(keyboardSize.height+height);

    [aboveKBView setFrame:CGRectMake(x, y, width, height)];
    [aboveKBView setHidden:NO];    
}
0 голосов
/ 18 февраля 2012

Попробуйте это

в viewDidLoad:

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

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

и добавьте эти методы.

- (void) keyboardWillShow: (NSNotification*) aNotification;
{   

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.3];

    CGRect rect = [[self view] frame];

    rect.origin.y -= 60; 

    [[self view] setFrame: rect];

    [UIView commitAnimations];

}

- (void) keyboardWillHide: (NSNotification*) aNotification;
{

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:0.3];

    CGRect rect = [[self view] frame];

    rect.origin.y += 60; 

    [[self view] setFrame: rect];

    [UIView commitAnimations];
}
0 голосов
/ 18 февраля 2012

Я нахожу эту страницу всегда очень полезной - она ​​показывает все важные размеры, поэтому легко вычислить нужный вам размер:

http://www.idev101.com/code/User_Interface/sizes.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...