Высота предложений UIKeyboard для уведомления iOS 8?

Я пытаюсь сохранить текстовое поле на клавиатуре в iOS 8. Но когда пользователь проводит пальцем вверх или вниз по верхней части клавиатуры, чтобы отобразить или отклонить варианты слов iOS 8, мне нужно уведомление о новой высоте клавиатуру, чтобы я мог перемещать текстовое поле вверх или вниз на эту высоту.

Как я могу это сделать?

Спасибо!


person Tony Friz    schedule 02.05.2015    source источник
comment
На самом деле клавиатура покажет, что уведомление имеет правильную высоту, но не в нужное время. Поэтому, когда окно предложений не отображается, оно будет показывать 271,00 на моем 6+ и 236,00, когда предложения видны.   -  person Tony Friz    schedule 02.05.2015


Ответы (3)


Вы можете зарегистрироваться в UIKeyboardDidShowNotification, а затем получить кадр клавиатуры из уведомления с помощью UIKeyboardFrameEndUserInfoKey.

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


- (void)handleKeyboardDidShowNotification:(NSNotification *)notification
{
    NSDictionary* info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    // Move your textview into view here
}

Это уведомление будет отправлено даже в том случае, если клавиатура уже отображается и только собирается изменить размер, поэтому вы будете получать его всякий раз, когда проводите пальцем вверх или вниз по верхней части клавиатуры.

person charmingToad    schedule 02.05.2015
comment
Отлично, это именно то, что мне было нужно. Большое спасибо. - person Tony Friz; 02.05.2015
comment
@charmingToad сработал, важная строка — UIKeyboardFrameEndUserInfoKey. - person Juan Boero; 30.11.2015

Вот некоторый код из пользовательского inputView, который я создал. Он даже обрабатывает кривую анимации для вашего пользовательского представления, чтобы она соответствовала скорости клавиатуры и двигалась вместе с ней.

Уведомление будет срабатывать при отображении/скрытии предложений.

- (void)registerForKeyboardNotifications {
    [[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 *)notification {
    NSDictionary* info = [notification userInfo];
    NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [info objectForKey: UIKeyboardAnimationCurveUserInfoKey];
    CGSize endKbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    CGRect baseFrame = self.frame;
    baseFrame.origin.y = CGRectGetMaxY(self.frame) - (endKbSize.height - 5);

    [UIView animateWithDuration:duration.floatValue delay:0.0f options:curve.integerValue animations:^{
        self.frame = baseFrame;
    } completion:^(BOOL finished) {
        self.frame = baseFrame;
    }]; }

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

    NSDictionary* info = [notification userInfo];
    NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [info objectForKey: UIKeyboardAnimationCurveUserInfoKey];

    [UIView animateWithDuration:duration.floatValue delay:0.0f options:curve.integerValue animations:^{
        self.frame = _originalRect;
    } completion:nil]; 
}
person Beau Nouvelle    schedule 02.05.2015

Swift 4 Решение:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardNotifications()
}

func registerKeyboardNotifications() {
    NotificationCenter.default.addObserver(self,
                                         selector: #selector(keyboardWillShow(notification:)),
                                         name: NSNotification.Name.UIKeyboardWillShow,
                                         object: nil)
    NotificationCenter.default.addObserver(self,
                                         selector: #selector(keyboardWillHide(notification:)),
                                         name: NSNotification.Name.UIKeyboardWillHide,
                                         object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}

@objc func keyboardWillShow(notification: NSNotification) {
    let userInfo: NSDictionary = notification.userInfo! as NSDictionary
    let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
    let keyboardSize = keyboardInfo.cgRectValue.size
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}

@objc func keyboardWillHide(notification: NSNotification) {
    scrollView.contentInset = .zero
    scrollView.scrollIndicatorInsets = .zero
}
person Community    schedule 21.06.2018