ios - 错误 : An -observeValueForKeyPath:ofObject:change:context: message was received but not handled

标签 ios swift xcode

我想根据内容动态设置 Collection View 的高度,我尝试了以下代码:

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    self.ItemCollection.addObserver(self , forKeyPath: "contentSize", options: NSKeyValueObservingOptions.old, context: nil)


}


func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutableRawPointer) {

    let newHeight : CGFloat = self.ItemCollection.collectionViewLayout.collectionViewContentSize.height

    var frame : CGRect! = self.ItemCollection.frame
    frame.size.height = newHeight

    self.ItemCollection.frame = frame


}    

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

            self.ItemCollection.removeObserver(self, forKeyPath: "contentSize")
}

我在这一行遇到错误:

 self.ItemCollection.addObserver(self , forKeyPath: "contentSize", options: NSKeyValueObservingOptions.old, context: nil)

错误如下:

An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: contentSize
Observed object: <UICollectionView: 0x102911200; frame = (0 275; 375 360);     clipsToBounds = YES; autoresize = W+TM+H+BM; gestureRecognizers = <NSArray: 0x1c4247a40>; layer = <CALayer: 0x1c02388a0>; contentOffset: {0, 0}; contentSize: {375, 0}; adjustedContentInset: {0, 0, 0, 0}> collection view layout: <UICollectionViewFlowLayout: 0x102543a80>
Change: {
kind = 1;
old = "NSSize: {20, 360}";
}
Context: 0x0'

最佳答案

Swift 4 中,它是一个覆盖函数,应该是 -

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) 

关于ios - 错误 : An -observeValueForKeyPath:ofObject:change:context: message was received but not handled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47150577/

相关文章:

ios - 从 ViewController 父类(super class)以编程方式添加 View 不会显示在前面

ios - 如何使用 Swift 回调闭包在 Controller 、检查器之间传递数据

ios - 如何将默认 iOS 元素解析为特定特征?

ios - 无法存档应用

ios - 如何使用 Xcode AutoLayout 调整图像大小?

ios - 首次加载后如何在 UICollectionView 中选择某些项目?

ios - UIView animateKeyFramesWithDuration 没有在正确的时间开始

ios - 在 Swift 中,如何等待一个动画在下一个动画开始之前完成?

ios - 可重复使用的 tableview 单元格相互影响而无需交互

ios - 如何使用 ios 中的一些输入数据创建 QR 码