问题描述
我正在尝试像这样观察collectionView.contentSize
:
I'm trying to observering collectionView.contentSize
like this :
func startObserveCollectionView() {
collectionView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.Old.union(NSKeyValueObservingOptions.New), context: &SearchDasboardLabelContext)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &SearchDasboardLabelContext {
if object === collectionView && keyPath! == "contentSize" {
print(change)
}
}
}
在xcode终端中,我得到一个NSSize
而不是CGSize
:
and in xcode terminal I got a NSSize
not CGSize
like this :
Optional(["old": NSSize: {320, 0}, "new": NSSize: {375, 39.5}, "kind": 1])
在Objective-C中,我使用了方法CGSizeValue
In objective-c I used method CGSizeValue
CGSize newContentSize = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];
有没有像CGSizeValue
这样的方法迅速
Is there any method like CGSizeValue
in swift
我已经尝试过快速var newContentSize = change[NSKeyValueChangeNewKey]?.CGSizeValue()
,但是出现了错误
I have tried in swift var newContentSize = change[NSKeyValueChangeNewKey]?.CGSizeValue()
but got error
需要帮助任何人吗?谢谢
need help anyone? Thanks
推荐答案
您在iOS上吗?因为我在,所以我做了同样的事情,并且提出了同样的问题.为什么NSSize
?也许这只是xcode终端在欺骗我们.
Are you on iOS? Because I am, I did the same thing and arrived at the same question; why NSSize
? Maybe that's just the xcode terminal playing a trick on us.
无论如何,您可以将其强制转换为NSValue
,然后就可以使用CGSizeValue
:
Anyway, you can cast it to an NSValue
then you will be able to use CGSizeValue
:
if let zeChange = change as? [NSString: NSValue] {
let oldSize = zeChange[NSKeyValueChangeOldKey]?.CGSizeValue()
let newSize = zeChange[NSKeyValueChangeNewKey]?.CGSizeValue()
}
这篇关于快速观察带有KVO的contentSize(CGSize)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!