我有以下代码:
func registerNotification(name:String, selector:Selector)
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil)
}
func registerKeyboardNotifications()
{
let isInPopover = navigationController?.popoverPresentationController != nil
let ignore = isInPopover && DEVICE_IS_IPAD
if !ignore {
registerNotification(UIKeyboardWillShowNotification, selector: Selector("keyboardWillShow:"))
registerNotification(UIKeyboardWillHideNotification, selector: Selector("keyboardWillHide:"))
}
}
在对UIViewController
进行扩展时,这段代码被许多视图控制器重用以注册键盘通知。但是,在Swift 2.2中,它会产生一个警告。我喜欢新的#selector
语法,但不确定如何在这种情况下实现它。
我认为正确的解决方案是创建一个协议,并仅为符合该协议的实例扩展UIViewController
。到目前为止,我的代码如下:
@objc protocol KeyboardNotificationDelegate
{
func keyboardWillShow(notification: NSNotification)
func keyboardWillHide(notification: NSNotification)
}
extension UIViewController where Self: KeyboardNotificationDelegate
{
func registerKeyboardNotifications()
{
let isInPopover = navigationController?.popoverPresentationController != nil
let ignore = isInPopover && DEVICE_IS_IPAD
if !ignore {
registerNotification(UIKeyboardWillShowNotification, selector: #selector(KeyboardNotificationDelegate.keyboardWillShow(_:)))
registerNotification(UIKeyboardWillHideNotification, selector: #selector(KeyboardNotificationDelegate.keyboardWillHide(_:)))
}
}
}
然而这会让我出现错误
trailing where clause for extension of non-generic type
在扩展行上。有什么想法吗?
extension UIViewController where Self: UICollectionViewDelegate
,但我没有意识到它需要与委托协议的位置相反,即将委托协议放在左边。 - barndog