其他分享
首页 > 其他分享> > Swift 添加KVO

Swift 添加KVO

作者:互联网

 

     
1.添加监听
   lab1.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil)



2. 监听
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let old = change?[NSKeyValueChangeKey.oldKey] {
          print("old = \(old)") //
        }
              
        if let new = change?[NSKeyValueChangeKey.newKey] {
          print("new = \(new)") // Albert
        }
    }


3.移除KVO
    deinit {
        lab1.removeObserver(self, forKeyPath: "text")
    }

 

2.添加多个KVO

       lab1.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil)
        lab1.addObserver(self, forKeyPath: "frame", options: .new, context: nil)



    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "text"{
            print("text改变")
        }else{
            print("frame 改变")
        }
        if let old = change?[NSKeyValueChangeKey.oldKey] {
          print("old = \(old)") //
        }
              
        if let new = change?[NSKeyValueChangeKey.newKey] {
          print("new = \(new)") // Albert
        }
    }

    deinit {
        lab1.removeObserver(self, forKeyPath: "text")
        lab1.removeObserver(self, forKeyPath: "frame")
    }

  

标签:old,KVO,self,lab1,添加,forKeyPath,text,new,Swift
来源: https://www.cnblogs.com/qingzZ/p/13746082.html