swift中的协议扩展

时间:2016-08-26 08:37:06

标签: swift

我的目标是:

所有UIViewController都采用Scrollable协议,并根据键盘将UIScrollView作为子视图处理滚动视图。

我的代码中有关错误的任何想法? :

  

Scrollable不是UIViewController的子类型

import Foundation

protocol Scrollable {
    var scrollview: UIScrollView { get }
    func registerForKeyboardNotifications()
}

extension Scrollable where Self: UIViewController {

    func registerForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(Self, selector: #selector(Scrollable.keyboardWasShown(_:)), name: "UIKeyboardDidShowNotification", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(Self, selector: #selector(Scrollable.keyboardWillBeHidden(_:)), name: "UIKeyboardWillHideNotification", object: nil)
    }

    func keyboardWasShown(aNotification: NSNotification) {

        if let keyboardSize = (aNotification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
            scrollview.contentInset = contentInsets
            scrollview.scrollIndicatorInsets = contentInsets
        }
    }

    func keyboardWillBeHidden(aNotification: NSNotification) {
        let contentInsets = UIEdgeInsetsZero
        scrollview.contentInset = contentInsets
        scrollview.scrollIndicatorInsets = contentInsets
    }
}

0 个答案:

没有答案