Подтвердить что ты не робот

Динамически получать раму клавиатуры

Можно ли динамически получить кадр, фактически его высоту, клавиатуры? Поскольку у меня есть UITextView, и я бы хотел настроить его высоту в соответствии с высотой кадра клавиатуры, когда изменяется метод ввода клавиатуры. Как вы знаете, разные методы ввода могут иметь разную высоту рамы клавиатуры.

4b9b3361

Ответ 1

попробуйте следующее:

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

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

// Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

//Given size may not account for screen rotation
int height = MIN(keyboardSize.height,keyboardSize.width);
int width = MAX(keyboardSize.height,keyboardSize.width);

//your other code here..........
}

Учебное пособие для более подробной информации

Ответ 2

Просто следуйте этому руководству от Apple, и вы получите то, что хотите. Документация Apple. Чтобы определить область, охватываемую клавиатурой, обратитесь к этому учебнику.

Ответ 3

Для пользователей Swift 3 код @Hector (с некоторыми дополнениями) будет выглядеть следующим образом:

В viewDidLoad добавить наблюдателя:

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: .UIKeyboardDidShow , object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: .UIKeyboardDidHide , object: nil)

Затем реализуем эти методы:

func keyboardDidShow(_ notification: NSNotification) {
     print("Keyboard will show!")
     // print(notification.userInfo)

     let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size
     print("Keyboard size: \(keyboardSize)")  

     let height = min(keyboardSize.height, keyboardSize.width)
     let width = max(keyboardSize.height, keyboardSize.width)

}

func keyboardDidHide(_ notification: NSNotification) {
        print("Keyboard will hide!")
}

Ответ 4

Вы можете добавить этот код в представление, которое содержит текстовое поле в Swift 3. Это заставит текстовое поле анимировать вверх и вниз с помощью клавиатуры.

private var keyboardIsVisible = false
private var keyboardHeight: CGFloat = 0.0

// MARK: Notifications

private func registerForKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
private func deregisterFromKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// MARK: Triggered Functions

@objc private func keyboardWillShow(notification: NSNotification) {
    keyboardIsVisible = true
    guard let userInfo = notification.userInfo else {
        return
    }
    if let keyboardHeight = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height {
        self.keyboardHeight = keyboardHeight
    }
    if !textField.isHidden {
        if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber,
            let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
            animateHUDWith(duration: duration.doubleValue,
                           curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut,
                           toLocation: calculateTextFieldCenter())
        }
    }
}

@objc private func keyboardWillBeHidden(notification: NSNotification) {
    keyboardIsVisible = false
    if !self.isHidden {
        guard let userInfo = notification.userInfo else {
            return
        }
        if let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber,
            let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
            animateHUDWith(duration: duration.doubleValue,
                           curve: UIViewAnimationCurve(rawValue: curve.intValue) ?? UIViewAnimationCurve.easeInOut,
                           toLocation: calculateTextFieldCenter())
        }
    }
}

// MARK: - Helpers

private func animateHUDWith(duration: Double, curve: UIViewAnimationCurve, toLocation location: CGPoint) {
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(TimeInterval(duration))
    UIView.setAnimationCurve(curve)
    textField.center = location
    UIView.commitAnimations()
}

private func calculateTextFieldCenter() -> CGPoint {
    if !keyboardIsVisible {
        return self.center
    } else {
        let yLocation = (self.view.frame.height - keyboardHeight) / 2
        return CGPoint(x: self.center.x, y: yLocation)
    }
}