Swift UIViewController 扩展属性: 扩展功能与实现
在 Swift 中,我们可以通过扩展来给 UIViewController 增加属性。下面是一个示例:
extension UIViewController {
private struct AssociatedKeys {
static var myCustomProperty: String?
}
var myCustomProperty: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.myCustomProperty) as? String
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.myCustomProperty, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
在上面的例子中,我们使用了 Objective-C 的 runtime 来实现属性的关联。通过定义一个私有的结构体 AssociatedKeys 来储存关联属性的键。然后,我们使用 objc_getAssociatedObject 和 objc_setAssociatedObject 方法来获取和设置关联属性的值。
现在,你可以在你的 UIViewController 的实例中使用 myCustomProperty 属性了:
let viewController = UIViewController()
viewController.myCustomProperty = "Hello, World!"
print(viewController.myCustomProperty) // 输出: Hello, World!
这样,你就成功给 UIViewController 增加了一个扩展属性。
原文地址: https://www.cveoy.top/t/topic/p66U 著作权归作者所有。请勿转载和采集!