【发布时间】:2018-02-13 16:17:42
【问题描述】:
我想创建一个自定义视图,当另一个对象(UIControl 的子类)上发生操作(如更改属性)时显示它
我的方法就是这样
- 创建一个 UIControl 对象可以遵循的协议
- 创建我可以观察我的委托的自定义视图
不幸的是,它不起作用,更糟糕的是,它崩溃了,因为编译器说“它不符合 kvc”
贝娄,我的代码:
protocol CustomDelegate: class where Self : UIControl {
func respondeToControl() -> Bool
}
class CustomView: UIView {
weak var delegate: CustomDelegate? {
didSet{
observeIfControlIsPressed()
}
}
func observeIfControlIsPressed(){
if delegate != nil {
let keypath = delegate! as! UIControl
keypath.addObserver(keypath,
forKeyPath: "backgroundColor",
options: [NSKeyValueObservingOptions.new, NSKeyValueObservingOptions.old],
context: nil)
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("background changed")
}
}
我的问题是,我如何重新设计我的解决方案来实现它 工作吗?
【问题讨论】:
标签: ios swift protocols key-value-observing cocoa-design-patterns