快速观察带有KVO的contentSize(CGSize) [英] observing contentSize (CGSize) with KVO in swift

查看:427
本文介绍了快速观察带有KVO的contentSize(CGSize)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样观察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

找不到成员'CGSizeValue'

could not find member 'CGSizeValue'

需要帮助任何人吗?谢谢

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆