Получение размера клавиатуры от userInfo в Swift
Я пытался добавить некоторый код, чтобы переместить мой взгляд вверх, когда появляется клавиатура, однако, у меня возникли проблемы, пытаясь перевести примеры Objective-C в Swift. Я сделал некоторый прогресс, но я застрял на одной конкретной линии.
Это два учебника / вопросы, которые я следовал:
как переместить содержимое UIViewController вверх по мере появления клавиатуры с помощью Свифт
http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears
вот код, который у меня сейчас есть:
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func keyboardWillShow(notification: NSNotification) {
var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
let frame = self.budgetEntryView.frame
frame.origin.y = frame.origin.y - keyboardSize
self.budgetEntryView.frame = frame
}
func keyboardWillHide(notification: NSNotification) {
//
}
На данный момент, я получаю ошибку на эту строку:
var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
Если кто-то может, дайте мне знать, что эта строка кода должна быть, я должна решать все сама.
10 ответов:
есть некоторые проблемы в вашей строке
var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
notification.userInfoвозвращает дополнительно словарь[NSObject : AnyObject]?, поэтому он должен быть развернут перед доступом к его значениям.- Цель-C
NSDictionaryсопоставляется с быстрым родным словарем, поэтому вы должны используйте синтаксис индекса словаря (dict[key]) для доступа к значениям.- значение должно быть приведено к
NSValueтак что вы можете называтьCGRectValueна нем.все это можно достигнуть с назначением сочетание из опционным, опционным приковывать и дополнительные слепки:
if let userInfo = notification.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) // ... } else { // no UIKeyboardFrameBeginUserInfoKey entry in userInfo } } else { // no userInfo dictionary in notification }или в одну стадию:
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) // ... }обновление 3.0.1 для Swift (Xcode версии 8.1):
if let userInfo = notification.userInfo { if let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) // ... } else { // no UIKeyboardFrameBeginUserInfoKey entry in userInfo } } else { // no userInfo dictionary in notification }или в одну стадию:
if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) // ... }
еще меньше кода на этой
Это было очень полезно для меня. Вам просто нужно включить ограничение вида в контроллер вида и использовать два добавленных наблюдателя. Затем просто используйте следующие методы (предполагается, что здесь вы перемещаете tableView)
func keyboardWillShow(sender: NSNotification) { if let userInfo = sender.userInfo { if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height { tableViewBottomConstraint.constant = keyboardHeight UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() }) } } }и
func keyboardWillHide(sender: NSNotification) { if let userInfo = sender.userInfo { if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height { tableViewBottomConstraint.constant = 0.0 UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() }) } } }
Если вы используете раскадровку, а не манипулируете самим видом, вы можете воспользоваться автоматической компоновкой.
(это очищенная версия ответа Николая)
Настройки Центр уведомлений, чтобы уведомить вас о появлении и исчезновении клавиатуры:
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) }и убедитесь, что вы удалите наблюдателей, когда они вам больше не нужны:
override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window) }внутри раскадровки, установите нижнее ограничение. Создание розетки из этого ограничения:
и установите постоянное свойство ограничения, когда клавиатура отображается или скрыта:
func keyboardWillShow(notification: NSNotification) { guard let keyboardHeight = (notification.userInfo! as NSDictionary).objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size.height else { return } nameOfOutlet.constant = keyboardHeight view.layoutIfNeeded() } func keyboardWillHide(notification: NSNotification) { nameOfOutlet.constant = 0.0 view.layoutIfNeeded() }Теперь, когда клавиатура появляется или исчезает, autolayout будет заботиться обо всем.
это помогло мне : https://developer.apple.com/library/ios/samplecode/UICatalog/Listings/Swift_UICatalog_TextViewController_swift.html
let userInfo = notification.userInfo! let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber).doubleValue let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue() let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()
Swift 2
func keyboardWasShown(notification:NSNotification) { guard let info:[NSObject:AnyObject] = notification.userInfo, let keyboardSize:CGSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size else { return } let insets:UIEdgeInsets = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0.0, keyboardSize.height, 0.0) self.scrollView.contentInset = insets self.scrollView.scrollIndicatorInsets = insets }Swift 3
func keyboardWasShown(notification:NSNotification) { guard let info:[AnyHashable:Any] = notification.userInfo, let keyboardSize:CGSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return } let insets:UIEdgeInsets = UIEdgeInsets(top: self.scrollView.contentInset.top, left: 0.0, bottom: keyboardSize.height, right: 0.0) self.scrollView.contentInset = insets self.scrollView.scrollIndicatorInsets = insets }
вы можете использовать эту строку для строки
var keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size
Swift 3: Обновление
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) 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, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window) }
Swift 3.0
вот пример извлечения размера клавиатуры и использования его для анимации представления вверх. В моем случае я перемещаю UIView, содержащий мои UITextFields вверх, когда пользователь начинает печатать, чтобы они могли заполнить форму и по-прежнему видеть кнопку отправки внизу.
я добавил выход к Нижний ограниченном пространстве из вида я хотел оживить и назвал его по имени
myViewsBottomSpaceConstraint:@IBOutlet weak var myViewsBottomSpaceConstraint: NSLayoutConstraint!затем я добавил следующий код для моего класса SWIFT:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) 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, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window) } func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo as! [String: NSObject] as NSDictionary let keyboardFrame = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! CGRect let keyboardHeight = keyboardFrame.height myViewsBottomSpaceConstraint.constant = keyboardHeight view.layoutIfNeeded() } func keyboardWillHide(notification: NSNotification) { myViewsBottomSpaceConstraint.constant = 0.0 view.layoutIfNeeded() }
подробности
xCode 8.2.1, swift 3
код
KeyboardNotifications
import Foundation class KeyboardNotifications { fileprivate var _isEnabled: Bool fileprivate var notifications: [KeyboardNotificationsType] fileprivate var delegate: KeyboardNotificationsDelegate init(notifications: [KeyboardNotificationsType], delegate: KeyboardNotificationsDelegate) { _isEnabled = false self.notifications = notifications self.delegate = delegate } deinit { if isEnabled { isEnabled = false } } } // MARK: - enums extension KeyboardNotifications { enum KeyboardNotificationsType { case willShow, willHide, didShow, didHide var selector: Selector { switch self { case .willShow: return #selector(KeyboardNotifications.keyboardWillShow(notification:)) case .willHide: return #selector(KeyboardNotifications.keyboardWillHide(notification:)) case .didShow: return #selector(KeyboardNotifications.keyboardDidShow(notification:)) case .didHide: return #selector(KeyboardNotifications.keyboardDidHide(notification:)) } } var notificationName: NSNotification.Name { switch self { case .willShow: return .UIKeyboardWillShow case .willHide: return .UIKeyboardWillHide case .didShow: return .UIKeyboardDidShow case .didHide: return .UIKeyboardDidHide } } } } // MARK: - isEnabled extension KeyboardNotifications { private func addObserver(type: KeyboardNotificationsType) { NotificationCenter.default.addObserver(self, selector: type.selector, name: type.notificationName, object: nil) print("\(type.notificationName.rawValue) inited") } var isEnabled: Bool { set { if newValue { for notificaton in notifications { addObserver(type: notificaton) } } else { NotificationCenter.default.removeObserver(self) print("Keyboard notifications deinited") } _isEnabled = newValue } get { return _isEnabled } } } // MARK: - Notification functions extension KeyboardNotifications { @objc func keyboardWillShow(notification: NSNotification) { delegate.keyboardWillShow?(notification: notification) } @objc func keyboardWillHide(notification: NSNotification) { delegate.keyboardWillHide?(notification: notification) } @objc func keyboardDidShow(notification: NSNotification) { delegate.keyboardDidShow?(notification: notification) } @objc func keyboardDidHide(notification: NSNotification) { delegate.keyboardDidHide?(notification: notification) } }KeyboardNotificationsDelegate
import Foundation @objc protocol KeyboardNotificationsDelegate { @objc optional func keyboardWillShow(notification: NSNotification) @objc optional func keyboardWillHide(notification: NSNotification) @objc optional func keyboardDidShow(notification: NSNotification) @objc optional func keyboardDidHide(notification: NSNotification) }использование
class ViewController: UIViewController { private var keyboardNotifications: KeyboardNotifications! override func viewDidLoad() { super.viewDidLoad() ... keyboardNotifications = KeyboardNotifications(notifications: [.willShow, .willHide, .didShow, .didHide], delegate: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardNotifications.isEnabled = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardNotifications.isEnabled = false } } extension ViewController: KeyboardNotificationsDelegate { // If you don't need this func you can remove it func keyboardWillShow(notification: NSNotification) { ... } // If you don't need this func you can remove it func keyboardWillHide(notification: NSNotification) { ... } // If you don't need this func you can remove it func keyboardDidShow(notification: NSNotification) { ... } // If you don't need this func you can remove it func keyboardDidHide(notification: NSNotification) { ... } }Полная Выборка
import UIKit class ViewController: UIViewController { private var keyboardNotifications: KeyboardNotifications! private var textField = UITextField(frame: CGRect(x: 40, y: 40, width: 200, height: 30)) override func viewDidLoad() { super.viewDidLoad() view.addSubview(textField) // when you will tap on view (background) the keyboard will hide // read about view.disableKeybordWhenTapped here: http://stackoverflow.com/a/42187286/4488252 view.disableKeybordWhenTapped = true keyboardNotifications = KeyboardNotifications(notifications: [.willShow, .willHide, .didShow, .didHide], delegate: self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardNotifications.isEnabled = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardNotifications.isEnabled = false } } extension ViewController: KeyboardNotificationsDelegate { // If you don't need this func you can remove it func keyboardWillShow(notification: NSNotification) { print("keyboardWillShow") let userInfo = notification.userInfo as! [String: NSObject] let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect print("keyboardFrame: \(keyboardFrame)") } // If you don't need this func you can remove it func keyboardWillHide(notification: NSNotification) { print("keyboardWillHide") } // If you don't need this func you can remove it func keyboardDidShow(notification: NSNotification) { print("keyboardDidShow") } // If you don't need this func you can remove it func keyboardDidHide(notification: NSNotification) { print("keyboardDidHide") } }результат
Log
для xamarin можно использовать c#6
private void KeyboardWillChangeFrame(NSNotification notification) { var keyboardSize = notification.UserInfo.ValueForKey(UIKeyboard.FrameEndUserInfoKey) as NSValue; if (keyboardSize != null) { var rect= keyboardSize.CGRectValue; //do your stuff here } }c#7
private void KeyboardWillChangeFrame(NSNotification notification) { if (!(notification.UserInfo.ValueForKey(UIKeyboard.FrameEndUserInfoKey) is NSValue keyboardSize)) return; var rect= keyboardSize.CGRectValue; }



Comments