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