2017-07-24 62 views
0

但是,目前在教程中,某些語法已過時。代碼基本上應該顯示並隱藏用戶鍵盤。我用addObserver方法得到了一些語法錯誤,Swift希望我使用關鍵路徑,但是,如果我使用自動'修復 - 它'我得到更多的錯誤。任何人都可以幫我解決這個問題嗎?謝謝!NSNotfication.addObserver - 更新到當前的Swift語法?

NSNotification.addObserver(self, selector: #selector(keyboardwillShow), name: .UIKeyboardWillShow, nil)  
NSNotification.addObserver(self, selector: #selector(keyboardwillHide), name: .UIKeyboardWillHide, nil) 


func keyboardwillShow(_notification:NSNotification) {  
    keyboard = (_notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue 
    UIView.animate(withDuration: 0.4) { 
     self.scrolledView.frame.size.height = self.scrollViewHeight - self.keyboard.height 
    } 
} 

func keyboardwillHide(_notification:NSNotification) { 
    UIView.animate(withDuration: 0.5) { 
     self.scrolledView.frame.size.height = self.view.frame.height 
    } 
} 

我得到的調試消息:"Incorrect argument labels in call(have _selector:name, expected _forKeyPath:options:context"

+0

您不會將觀察者添加到'NSNotification',您應該將它們添加到'NotificationCenter.default' – dan

+0

Isnt Notification Center.default在Swift 3中不可用嗎? – Prometheus

+0

它仍然可用 – dan

回答

1

你的函數參數,那就是缺少當您在觀看

加它,你必須使用NotificationCenter.default.addObserver沒有NotificationCenter.addObserver

let selectorForKeyBoardWillShow: Selector = #selector(ViewController.keyboardWillShow(_:)) 
let selectorForKeyBoardWillHide: Selector = #selector(ViewController.keyboardWillHide(_:)) 

    // MARK: - Functions 
override func viewDidLoad() { 
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillShow, name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
    NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillHide, name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
} 


// MARK: Keyboard Observer 
func keyboardWillShow(_ notification: Notification) { 
} 

func keyboardWillHide(_ notification: Notification) { 
} 
+0

太棒了!林不知道爲什麼,但我曾嘗試使用NotificationCenter之前,它沒有奏效。無論如何,謝謝! – Prometheus