在我的扩展程序中,我以这种方式放置了用于键盘通知的控件

protocol KeyboardSpaceProtocol {
    func addObservers()
    func removeObservers()
    func keyboardWillShow(notification:NSNotification) -> CGFloat
}

extension UIView: KeyboardSpaceProtocol {

    func addObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
    }

    func removeObservers() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func keyboardWillShow(notification:NSNotification) -> CGFloat {
        let userInfo:NSDictionary = notification.userInfo!
        let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.CGRectValue()
        return keyboardRectangle.height
    }
}


现在我想在UIView类中更新CGFloat值(keyboardheight)...如何在视图控制器中使用?我不知道键盘何时熄灭以及如何更新我的值。
有什么建议么?

最佳答案

您可以使用objc_associatedObject在运行时添加属性。

我的示例使用UIViewController而不是UIView只是因为它对我来说似乎更合逻辑。

import Foundation
import UIKit
import ObjectiveC

protocol KeyboardSpaceProtocol {
    func addObservers()
    func removeObservers()
    func keyboardWillShow(notification:NSNotification) -> CGFloat
    var keyBoardHeight: CGFloat {get set}
}

private var keyBoardKey: UInt8 = 0
extension  UIViewController: KeyboardSpaceProtocol {

    var keyBoardHeight: CGFloat {
        get {
            return objc_getAssociatedObject(self, &keyBoardKey) as! CGFloat
        }
        set { objc_setAssociatedObject(self, &keyBoardKey, newValue,  objc_AssociationPolicy(rawValue: 0)!) }
    }

    func addObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
    }

    func removeObservers() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func keyboardWillShow(notification:NSNotification) -> CGFloat {
        let userInfo:NSDictionary = notification.userInfo!
        let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.CGRectValue()

        var selfAsProtocol = self as KeyboardSpaceProtocol
        selfAsProtocol.keyBoardHeight = keyboardRectangle.height

        return keyboardRectangle.height
    }
}

关于ios - iOS:在扩展程序中从NSNotificationCenter返回值(Swift),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38821293/

10-10 17:50