Высота клавиатуры на разных устройствах iOS различна. Кто-нибудь знает, как я могу получить высоту клавиатуры устройства программно?
Как получить высоту клавиатуры?
Ответ 1
В Свифте:
Вы можете получить высоту клавиатуры, подписавшись на уведомление UIKeyboardWillShowNotification
. (Предполагая, что вы хотите знать, какой будет высота, прежде чем она будет показана).
Что-то вроде этого:
Swift 2
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
Свифт 3
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
Swift 4
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
Затем вы можете получить доступ к высоте в функции keyboardWillShow
следующим образом:
Swift 2
func keyboardWillShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo!
let keyboardFrame: NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
}
Свифт 3
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
Swift 4
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}
Ответ 2
Swift 3.0 и Swift 4.1
1- Зарегистрируйте уведомление в методе viewWillAppear
:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
2- Способ вызова:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
print(keyboardHeight)
}
}
Ответ 3
Swift 4 и ограничения
В вашем представлении таблицы добавьте нижнее ограничение относительно нижней безопасной области. В моем случае ограничение называется tableViewBottomLayoutConstraint.
@IBOutlet weak var tableViewBottomLayoutConstraint: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(notification:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow , object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide , object: nil)
}
@objc
func keyboardWillAppear(notification: NSNotification?) {
guard let keyboardFrame = notification?.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardHeight: CGFloat
if #available(iOS 11.0, *) {
keyboardHeight = keyboardFrame.cgRectValue.height - self.view.safeAreaInsets.bottom
} else {
keyboardHeight = keyboardFrame.cgRectValue.height
}
tableViewBottomLayoutConstraint.constant = keyboardHeight
}
@objc
func keyboardWillDisappear(notification: NSNotification?) {
tableViewBottomLayoutConstraint.constant = 0.0
}
Ответ 4
Обновление Swift 4.2
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: UIResponder.keyboardWillShowNotification, object: nil)
}
метод выбора:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
расширение:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Обновить Swift 3.0
private func setUpObserver() {
NotificationCenter.default.addObserver(self, selector: .keyboardWillShow, name: .UIKeyboardWillShow, object: nil)
}
метод выбора:
@objc fileprivate func keyboardWillShow(notification:NSNotification) {
if let keyboardRectValue = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardRectValue.height
}
}
расширение:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(notification:))
}
Совет
UIKeyboardDidShowNotification или UIKeyboardWillShowNotification могут вызываться дважды и получать другой результат, в этой статье объясняется, почему вызывается дважды.
В Swift 2.2
Swift 2.2 не поддерживает использование строк для селекторов и вместо этого вводит новый синтаксис: #selector
.
Что-то вроде:
private func setUpObserver() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: .keyboardWillShow, name: UIKeyboardWillShowNotification, object: nil)
}
метод выбора:
@objc private func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo!
let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
editorBottomCT.constant = keyboardHeight
}
расширение:
private extension Selector {
static let keyboardWillShow = #selector(YourViewController.keyboardWillShow(_:))
}
Ответ 5
Более короткая версия здесь:
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
}
}
Ответ 6
Swift 4.
Простейший метод
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardHeight",keyboardHeight)
}
}
Ответ 7
//Шаг 1: - Register NotificationCenter
ViewDidLoad() {
self.yourtextfield.becomefirstresponder()
// Register your Notification, To know When Key Board Appears.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
// Register your Notification, To know When Key Board Hides.
NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//Шаг 2: - Эти методы будут называться автоматически при открытии клавиатуры или скрываются
func keyboardWillShow(notification:NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
}
func keyboardWillHide(notification:NSNotification) {
tblViewListData.frame.size.height = fltTblHeight
}
Ответ 8
Для кода от Apple для элементов управления UIKit, включая клавиатуры, вверх https://developer.apple.com/library/content/samplecode/UICatalog/Listings/Swift_UIKitCatalog_TextFieldViewController_swift.html#//apple_ref/doc/uid/DTS40007710-Swift_UIKitCatalog_TextFieldViewController_swift-DontLinkElementID_85 Загружаемый код, который можно использовать почти "из коробки"
Ответ 9
Я использовал тот же метод в своем коде, но когда я попробовал его в ландшафтном режиме, он возвращает 56 для высоты! Есть идеи??
Ответ 10
Метод от ZAFAR007 обновлен для Swift 5 в Xcode 10
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight : Int = Int(keyboardSize.height)
print("keyboardHeight",keyboardHeight)
}
}
Ответ 11
Swift 5
override func viewDidLoad() {
// Registering for keyboard notification.
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
/* UIKeyboardWillShowNotification. */
@objc internal func keyboardWillShow(_ notification : Notification?) -> Void {
var _kbSize:CGSize!
if let info = notification?.userInfo {
let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
// Getting UIKeyboardSize.
if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
let screenSize = UIScreen.main.bounds
//Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
let intersectRect = kbFrame.intersection(screenSize)
if intersectRect.isNull {
_kbSize = CGSize(width: screenSize.size.width, height: 0)
} else {
_kbSize = intersectRect.size
}
print("Your Keyboard Size \(_kbSize)")
}
}
}