web-dev-qa-db-ja.com

NSNotificationCenter Swift 3.0キーボードの表示および非表示

キーボードが表示および非表示になったときに次のコードを使用して関数を実行しようとしています。

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ViewController.keyBoardUp(Notification :)), name:  NSNotification.Name.UIKeyboardWillShow, object: nil)

そして、以下のkeyBoardUp関数:

func keyBoardUp( Notification: NSNotification){
    print("HELLO")
}

ただし、キーボードが表示されている場合、関数はコンソールに出力しません。ヘルプは大歓迎です

15
Dhwanit Zaveri

スウィフト3:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: Notification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: Notification.Name.UIKeyboardWillHide, object: nil)

}

func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        print("notification: Keyboard will show")
        if self.view.frame.Origin.y == 0{
            self.view.frame.Origin.y -= keyboardSize.height
        }
    }

}

func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y != 0 {
            self.view.frame.Origin.y += keyboardSize.height
        }
    }
}

Swift 4.2.1:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

@objc fileprivate func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

@objc fileprivate func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        // Do something with size
    }
}

Swift 4.2 +

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y == 0{
            self.view.frame.Origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y != 0 {
            self.view.frame.Origin.y += keyboardSize.height
        }
    }
}
29
Vandana

Swift 4.2+

@ vandana's 回答が反映されるように更新されましたchanges Swift 4.2。

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

}

@objc func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        print("notification: Keyboard will show")
        if self.view.frame.Origin.y == 0{
            self.view.frame.Origin.y -= keyboardSize.height
        }
    }

}

@objc func keyboardWillHide(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y != 0 {
            self.view.frame.Origin.y += keyboardSize.height
        }
    }
}

また、UIKeyboardFrameEndUserInfoKeyを使用して、iOS 11で導入されたsafeAreaInsetの変更を考慮する必要があります。

26
Rakesha Shastri

キーボード通知オブザーバーを設定する

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

そしてあなたの関数でそれを処理します

func keyboardNotification(notification: NSNotification) {
  print("keyboard displayed!!")
}

これがあなたのお役に立てば幸いです。

5
Pankaj

Swift 4.X/5

私はすでに長い間利用可能なインラインのブロックベースのアプローチが好きです! addObserver(...)here のパラメーターについて詳しく読むことができます。

このアプローチの利点は次のとおりです。

  • @objcキーワードを使用する必要はありません
  • オブザーバーをセットアップした場所と同じ場所にコールバックコードを記述します

重要:オブザーバの登録を設定したオブジェクトのdeinitNotificationCenter.default.removeObserver(observer)を呼び出します(多くの場合、View Controller )。

let center = NotificationCenter.default

let keyboardWillShowObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
    guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
    let height = value.cgRectValue.height

    // use the height of the keyboard to layout your UI so the prt currently in
    // foxus remains visible
}

let keyboardWillHideObserver: NSObjectProtocol = center.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in

    // restore the layout of your UI before the keyboard has been shown
}
2
blackjacx

Swift 4.2

このバージョンは、iPhone 5とiPhone Xの両方で機能します。制約設定中に安全な領域を尊重すれば、非常にうまく機能します。

override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWillShow(notification: NSNotification) {
        if let _ = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.view.frame.Origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
            if self.emailTextField.isFirstResponder {
                self.view.frame.Origin.y -= 100
            } else if self.passwordTextField.isFirstResponder {
                self.view.frame.Origin.y -= 150
            } else if self.passwordConfirmTextField.isFirstResponder {
                self.view.frame.Origin.y -= 200
            }
        }
}

@objc func keyboardWillHide(notification: NSNotification) {
        if self.view.frame.Origin.y != 0 {
           self.view.frame.Origin.y = self.navigationController!.navigationBar.frame.size.height + UIApplication.shared.statusBarFrame.size.height
        }
}
1

Swift用に更新:

// MARK:- Kyeboard hide/show methods

func keyboardWasShown(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y == 0{
            self.view.frame.Origin.y -= keyboardSize.height
        }
    }
}

func keyboardWillBeHidden(_ notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.Origin.y != 0{
            self.view.frame.Origin.y += keyboardSize.height
        }
    }
}

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: true, moveValue: 120)
    }
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField == mEnterPasswordTextField || textField == mEnterConfirmPassword  {
            animateViewMoving(up: false, moveValue: 120)
    }
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)
    UIView.commitAnimations()
}

// In viewDidLoad()

self.registerForKeyboardNotifications()
self.deregisterFromKeyboardNotifications()
1
Kiran jadhav

Swift 4.2

NotificationCenter.default.addObserver(self, selector: #selector(didReceiveKeyboardNotificationObserver(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveKeyboardNotificationObserver(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

@objc func didReceiveKeyboardNotificationObserver(_ notification: Notification) {
    let userInfo = notification.userInfo
    let keyboardBounds = (userInfo!["UIKeyboardBoundsUserInfoKey"] as! NSValue).cgRectValue
    let keyboardFrame = (userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
    let duration = userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
    let curve = userInfo!["UIKeyboardAnimationCurveUserInfoKey"] as! Int
    let frameBegin = (userInfo!["UIKeyboardFrameBeginUserInfoKey"] as! NSValue).cgRectValue
    let centerBegin = (userInfo!["UIKeyboardCenterBeginUserInfoKey"] as! NSValue).cgPointValue
    let center = (userInfo!["UIKeyboardCenterEndUserInfoKey"] as! NSValue).cgPointValue
    let location = userInfo!["UIKeyboardIsLocalUserInfoKey"] as! Int
    println("keyboardBounds: \(keyboardBounds) \nkeyboardFrame: \(keyboardFrame) \nduration: \(duration) \ncurve: \(curve) \nframeBegin:\(frameBegin) \ncenterBegin:\(centerBegin)\ncenter:\(center)\nlocation:\(location)")
    switch notification.name {
    case UIResponder.keyboardWillShowNotification:
    // keyboardWillShowNotification
    case UIResponder.keyboardWillHideNotification:
    // keyboardWillHideNotification
    default:
        break
    }
}
1
Giang

これを試して

 override func viewDidLoad()
    {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

 @objc func keyboardWillShow(notification: NSNotification) {
      if(messageCount > 0)
      {
        tableView.scrollToRow(at: IndexPath(item:messageCount - 1, section: 0), at: .bottom, animated: true)
      }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if(messageCount > 0)
    {
        tableView.scrollToRow(at: IndexPath(item:0, section: 0), at: .top, animated: true)
    }
}
1
Sreeraj VR