Frage Tastaturgröße von userInfo in Swift abrufen


Ich habe versucht, Code hinzuzufügen, um meine Ansicht zu verschieben, wenn die Tastatur angezeigt wird, jedoch habe ich Probleme, die Objective-C-Beispiele in Swift zu übersetzen. Ich habe Fortschritte gemacht, aber ich stehe auf einer bestimmten Linie fest.

Dies sind die beiden Tutorials / Fragen, denen ich gefolgt bin:

Wie Sie den Inhalt von UIViewController nach oben bewegen, wenn das Keypad mit Swift angezeigt wird http://www.ioscreator.com/tutorials/move-view-when-keyboard- erscheint

Hier ist der Code, den ich derzeit habe:

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) {
    //
}

Im Moment bekomme ich einen Fehler in dieser Zeile:

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))

Wenn mir jemand sagen könnte, was diese Codezeile sein soll, sollte ich es schaffen, den Rest selbst herauszufinden.


75
2017-08-22 15:54


Ursprung


Antworten:


Es gibt einige Probleme in Ihrer Linie

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
  • notification.userInfo gibt ein zurück wahlweise Wörterbuch [NSObject : AnyObject]?, Daher muss es vor dem Zugriff auf seine Werte ausgepackt werden.
  • Das Ziel-C NSDictionary ist ein Swift native Dictionary zugeordnet, also müssen Sie Verwenden Sie die Wörterbuch-Subscript-Syntax (dict[key]) um auf die Werte zuzugreifen.
  • Der Wert muss in umgewandelt werden NSValue damit du anrufen kannst CGRectValue darauf.

All dies kann mit einer Kombination aus optionaler Zuweisung, optionaler Verkettung und optionale Modelle:

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
}

oder in einem Schritt:

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}

Update für Swift 3.0.1 (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
}

oder in einem Schritt:

if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}

179
2017-08-22 16:15



Für noch weniger Code betrachten betrachten DIES

Es war sehr hilfreich für mich. Sie müssen nur die View-Einschränkung in den View-Controller aufnehmen und die beiden hinzugefügten Beobachter verwenden. Dann benutze einfach die folgenden Methoden (hier soll ein TableView verschoben werden)

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()
                })
            }
        }
    }

und

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() })
  }
} }

17
2018-03-29 07:42



Wenn Sie ein Storyboard verwenden, anstatt die Ansicht selbst zu bearbeiten, können Sie das automatische Layout nutzen.

(Dies ist eine bereinigte Version von Nikolaus Antwort)

Richten Sie das Benachrichtigungscenter ein, um Sie über das Erscheinen und Verschwinden der Tastatur zu informieren:

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)

}

Und stellen Sie sicher, dass Sie die Beobachter entfernen, wenn Sie sie nicht mehr brauchen:

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)
}

Innerhalb des Storyboards legen Sie die untere Einschränkung fest. Erstellen Sie einen Ausgang dieser Einschränkung:

enter image description here

und legen Sie die Konstanteneigenschaft der Abhängigkeit fest, wenn die Tastatur ein- oder ausgeblendet wird:

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()
}

Jetzt, wenn die Tastatur erscheint oder verschwindet, wird automatisches Layout alles erledigen.


10
2018-03-16 02:27



Das hat mir geholfen: 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()

3
2018-02-24 20:21



Schnell 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
    }

Schnell 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
}

3
2018-03-24 17:45



Sie können diese eine Zeile für Ihre Zeile verwenden

var keyboardSize:CGSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue().size

1
2018-01-19 09:33



Schnell 3: UPDATE

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)
}

1
2017-12-18 17:28



Schnelles 3.0

Im Folgenden finden Sie ein Beispiel für das Abrufen der Tastaturgröße und die Verwendung einer Animation, um eine Ansicht nach oben zu animieren. In meinem Fall verschiebe ich eine UIView, die meine UITextFields enthält, nach oben, wenn ein Benutzer mit der Eingabe beginnt, damit sie ein Formular ausfüllen können und die Schaltfläche "Senden" unten angezeigt wird.

Ich habe eine Steckdose hinzugefügt Bodenraumbeschränkung von der Aussicht wollte ich animieren und nannte sie benannt myViewsBottomSpaceConstraint:

@IBOutlet weak var myViewsBottomSpaceConstraint: NSLayoutConstraint!

Dann habe ich meiner Swift-Klasse den folgenden Code hinzugefügt:

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()
}

0
2018-01-08 16:42



Einzelheiten

xCode 8.2.1, schnelle 3

Code

KeyboardNotifikationen

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)
}

Verwendung

 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) {
           ...
    }
}

Volles Beispiel

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")
    }
}

Ergebnis

enter image description here

Log

enter image description here


0
2018-03-04 19:03



Für Xamarin können Sie verwenden 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;
   }

0
2017-09-19 19:45