I\'m trying to update this code to swift 3:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(\"keyboardWillShow:\"), name: UIKeyboar
For Swift 4.2
.UIKeyboardWillShow
is renamed to UIResponder.keyboardWillShowNotification
and
.UIKeyboardWillHide
is renamed to 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
}
@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 = $0.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)
}
NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillShow:")), name:UIResponder.keyboardWillShowNotification, object: nil);
NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillHide:")), name:UIResponder.keyboardWillHideNotification, object: nil);
You can perform keyboard notification on both version of Swift respectively.
Add Objserver:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardWillShow, object: nil)
Call function swift 3
func keyboardDidShow() {
print("keyboardDidShow")
}
Call function In swift 4
@objc func keyboardDidShow() {
print("keyboardDidShow")
}