ios 如何在 Swift 3 中编写键盘通知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37875973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:26:13  来源:igfitidea点击:

How to write Keyboard notifications in Swift 3

iosswiftswift3nsnotificationcenter

提问by David DelMonte

I'm trying to update this code to swift 3:

我正在尝试将此代码更新为 swift 3:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)`

So far, I've just tried the auto corrections given by the compiler. This results in code like this:

到目前为止,我刚刚尝试了编译器给出的自动更正。这导致如下代码:

let notificationCenter = NotificationCenter.default()
notificationCenter.addObserver(self, selector: Selector(("keyboardWillShow:")), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

notificationCenter.addObserver(self, selector: Selector(("keyboardWillHide:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)`

Unfortunately, that doesn't take me far, resulting in additional errors.

不幸的是,这并没有让我走多远,导致了额外的错误。

Has anyone solved this please?

请问有人解决了吗?

Please note that I'm just trying how to write the notifications. I'm not (yet) trying to fix the notification functions.. Thanks

请注意,我只是在尝试如何编写通知。我还没有(还)试图修复通知功能..谢谢

回答by fssilva

Swift 4.2 Xcode 10 (10L213o)

斯威夫特 4.2 Xcode 10 (10L213o)

The main changes compared with Swift 3 are in the UIWindow.keyboardWillShowNotificationand UIWindow.keyboardWillHideNotification

与 Swift 3 相比的主要变化是在UIWindow.keyboardWillShowNotificationUIWindow.keyboardWillHideNotification

let notifier = NotificationCenter.default
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)),
                     name: UIWindow.keyboardWillShowNotification,
                     object: nil)
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)),
                     name: UIWindow.keyboardWillHideNotification,
                     object: nil)


@objc
func keyboardWillShowNotification(_ notification: NSNotification) {}

@objc
func keyboardWillHideNotification(_ notification: NSNotification) {}

回答by ZAFAR007

Swift 4

斯威夫特 4

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

func keyboardWillShow(notification: NSNotification) {
     print("keyboardWillShow")
}

func keyboardWillHide(notification: NSNotification){
     print("keyboardWillHide")
}

You can also get keyboard info using below code inside these methods.

您还可以在这些方法中使用以下代码获取键盘信息。

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil) .      

@objc func keyboardWillChange(notification: NSNotification) {
     let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
     let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
     let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
     let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
     let deltaY = targetFrame.origin.y - curFrame.origin.y
 }

回答by Ben Rawner

I fixed this issue by writing the code like this

我通过编写这样的代码解决了这个问题

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

回答by Vigneshraj Sekarbabu

For Swift 4.2 .UIKeyboardWillShowis renamed to UIResponder.keyboardWillShowNotificationand .UIKeyboardWillHideis renamed to UIResponder.keyboardWillHideNotification

对于雨燕4.2 .UIKeyboardWillShow被重命名为UIResponder.keyboardWillShowNotification.UIKeyboardWillHide被重命名为UIResponder.keyboardWillHideNotification

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

   @objc func NameOfSelector() {
       //Actions when notification is received
    }

回答by Vigneshraj Sekarbabu

You can replace the deprecated string literal Selectorwith the type-checked #selector(Class.method)pair:

您可以使用Selector类型检查#selector(Class.method)对替换已弃用的字符串文字:

let center = NotificationCenter.default
center.addObserver(self,
                   selector: #selector(keyboardWillShow(_:)),
                   name: .UIKeyboardWillShow,
                   object: nil)

center.addObserver(self,
                   selector: #selector(keyboardWillHide(_:)),
                   name: .UIKeyboardWillHide,
                   object: nil)

The #selectorsyntax is much safer, since Swift is able to check at compile time that the specified method actually exists.

#selector语法是要安全得多,因为斯威夫特是能够检查在该指定的方法确实存在编译时间。

For more information about Swift selectors, see rickster's detailed answer.

有关 Swift 选择器的更多信息,请参阅rickster 的详细回答

回答by Sergey

Swift 5.1 + Combine + SwiftUI

Swift 5.1 + 组合 + SwiftUI

@State var keyboardHeight: CGFloat = 0 // or @Published if one is in ViewModel: ObservableObject

private var cancellableSet: Set<AnyCancellable> = []

init() {

   let notificationCenter = NotificationCenter.default

   notificationCenter.publisher(for: UIWindow.keyboardWillShowNotification)
       .map {
             guard
                 let info = 
 override func viewDidLoad()
    {
        super.viewDidLoad()
 NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}
.userInfo, let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return 0 } return keyboardFrame.height } .assign(to: \.keyboardHeight, on: self) .store(in: &cancellableSet) notificationCenter.publisher(for: UIWindow.keyboardDidHideNotification) .map { _ in 0 } .assign(to: \.keyboardHeight, on: self) .store(in: &cancellableSet) }

回答by Amul4608

In Swift 3.0

在 Swift 3.0 中

func keyboardWillShow(notification: NSNotification) 
{

      // Your Code Here
}

func keyboardWillHide(notification: NSNotification)
{  
   //Your Code Here     
}

Keybord Show and Hide

键盘显示和隐藏

NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardWillShow, object: nil)

回答by Tech

You can perform keyboard notification on both version of Swift respectively.

您可以分别在两个版本的 Swift 上执行键盘通知。

Add Objserver:

添加对象服务器:

func keyboardDidShow() {
          print("keyboardDidShow")
       }

Call function swift 3

调用函数swift 3

@objc func keyboardDidShow() {
      print("keyboardDidShow")
   }

Call function In swift 4

调用函数在swift 4

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

回答by SCS

class ChatVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

// reference to your UIView with message TextField

    @IBOutlet weak var ChatView: UIView!   


// bottom constrain to your UIView (in my case ChatView)

    var bottomConstraint: NSLayoutConstraint?  

    override func viewDidLoad() {
        super.viewDidLoad()

// add some text in the placeholder if you want

        messageField.placeholder = "Type your message.." 

// here we add two notifications for showing and hiding the keyboard

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

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


// defines the start position for message textField that will be shown on the screen

        bottomConstraint = NSLayoutConstraint(item: ChatViewField!, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: -40)    
        view.addConstraint(bottomConstraint!)    
    }

// handles notifications for both cases when keyboard pops up and disappears  

  @objc func handleKeyboardNotification(notification: NSNotification){
        if let userInfo = notification.userInfo {

            let keyboardFrame =  (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
            print(keyboardFrame)

            let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification

            bottomConstraint?.constant = isKeyboardShowing ? -keyboardFrame.height : -40

// makes animation at the same time as the keyboard

UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {

                self.view.layoutIfNeeded()
            }) { (completed) in    
            }   
        }
    }

回答by Ivan.I

Here is the best solution that works for me as far (used from "Lets Build That App" YouTube channel)

这是迄今为止对我有用的最佳解决方案(来自“Lets Build That App”YouTube频道)

##代码##