Подтвердить что ты не робот

Как написать уведомления о клавиатуре в Swift 3

Я пытаюсь обновить этот код, чтобы быстро 3:

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

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

Пока что я только что попробовал автокоррекции, предоставленные компилятором. В результате получается такой код:

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

К сожалению, это не займет у меня много времени, что приведет к дополнительным ошибкам.

Кто-нибудь решил это, пожалуйста?

Обратите внимание, что я просто пытаюсь написать уведомление. Я (пока) не пытаюсь исправить функции уведомлений.. Спасибо

4b9b3361

Ответ 1

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

Вы также можете получить информацию о клавиатуре Uisng Ниже кода внутри этих методов.

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
 }

Ответ 2

Swift 4.2 Xcode 10 (10L213o)

Основные изменения по сравнению со Swift 3 находятся в UIWindow.keyboardWillShowNotification и UIWindow.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) {}

Ответ 3

Я исправил эту проблему, написав код, подобный этому

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

Ответ 4

Для Swift 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
    }

Ответ 5

Вы можете заменить устаревший строковый литерал 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)

Синтаксис #selector гораздо безопаснее, так как Swift может проверить во время компиляции, что указанный метод действительно существует.

Дополнительные сведения о селекторах Swift см. в подробном ответе rickster.

Ответ 6

В Swift 3.0

 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)

}

Показ и скрытие клавиш >

func keyboardWillShow(notification: NSNotification) 
{

      // Your Code Here
}

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

Ответ 7

Вы можете выполнять уведомление клавиатуры на обеих версиях Swift соответственно.

Добавить Objserver:

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

Функция вызова swift 3

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

Функция вызова В режиме быстрого 4

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

Ответ 8

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