添加一个view并在view上加一个单击手势
self.tapGeview = UIView.init(frame: CGRect(origin:CGPoint(x:100,y:200),size:CGSize(width:200, height:100)));
//添加一个手势
let tapGe:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action:#selector(tapGeBlicked(tap:)))
self.tapGeview?.addGestureRecognizer(tapGe)
self.tapGeview?.backgroundColor = UIColor.orange
self.view.addSubview(self.tapGeview!)
响应单击手势
@objc func tapGeBlicked(tap:UITapGestureRecognizer) -> Void {
print("手势单击")
}
添加kvo监听
创建一个kvo监听的类,并定义一个要监听的对象
image.png
创建一个kvcPer的对象
var kvoer:kvcPer?
初始化,并添加监听
self.kvoer = kvcPer();
self.kvoer?.addObserver(self, forKeyPath:"kvotest", options: .new, context:nil)
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "kvotest" {
print("kvo监听\(String(describing: kvoer?.kvotest))")
}
if (object as? kvcPer == kvoer) {
print("kvo监听xxxxxxx")
} else {
}
}
在刚才的单击响应的函数添加监听的触发(值的改变)
@objc func tapGeBlicked(tap:UITapGestureRecognizer) -> Void {
print("手势单击")
kvoer?.setValue("手势单击响应监听", forKeyPath: "kvotest")
}
单击最开始创建的view就能看到监听的结果
网友评论