gpt4 book ai didi

iOS:在扩展中从 NSNotificationCenter 返回值(swift)

转载 作者:行者123 更新时间:2023-11-30 13:10:19 25 4
gpt4 key购买 nike

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

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)...如何在 View Controller 中更新?我不知道键盘何时熄灭以及如何更新我的值。有什么建议吗?

最佳答案

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

我的示例使用 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:在扩展中从 NSNotificationCenter 返回值(swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38821293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com