首页 > 解决方案 > swift UITableView/ UICollectionView 调用观察(\.xxx)不起作用

问题描述

collection.addObserver(self, forKeyPath: #keyPath(UICollectionView.contentSize), options: .new, context: nil)

 collection.observe(\.contentSize) { (collection, change) in
         
  } 

当我使用“addObserver”观察 contentSize 时,它​​起作用了,但是观察(.contentSize)不起作用,我不知道为什么。

标签: iosswift

解决方案


与此处的示例进行比较:

class MyObserver: NSObject {
    @objc var objectToObserve: MyObjectToObserve
    var observation: NSKeyValueObservation?
    
    init(object: MyObjectToObserve) {
        objectToObserve = object
        super.init()
        
        observation = observe(
            \.objectToObserve.myDate,
            options: [.old, .new]
        ) { object, change in
            print("myDate changed from: \(change.oldValue!), updated to: \(change.newValue!)")
        }
    }
}

观察方法返回一个“观察”标记,你需要抓住它。它停止观察是否/何时超出范围。


推荐阅读