1
我想在UIView上创建一个设置方法,通过一个扩展来允许我通过新的Swift 4 KeyPaths设置颜色。如果我做了以下我得到的错误Cannot assign to immutable expression of type 'UIColor?'
是否可以在扩展中通过Swift 4 KeyPaths在UIView上设置属性?
extension UIView {
func set(color: UIColor, forKeyPath path: KeyPath<UIView, UIColor?>) {
self[keyPath: path] = color // Error: Cannot assign to immutable expression of type 'UIColor?'
}
}
view.set(color: .white, forKeyPath: \.backgroundColor)
如果我使用这个扩展之外,它工作正常:
let view = UIView()
let path = \UIView.backgroundColor
view[keyPath: path] = .white // Works fine
而且使用的keyPath的旧式正常工作:
extension UIView {
func set(color: UIColor, forKeyPath path: String) {
self.setValue(color, forKey: path)
}
}
view.set(color: .white, forKeyPath: #keyPath(UIView.backgroundColor))
感谢您的帮助。
那完美。 – Radther