gpt4 book ai didi

xcode - swift 使用 KVO 观察 contentSize (CGSize)

转载 作者:搜寻专家 更新时间:2023-10-30 22:08:55 32 4
gpt4 key购买 nike

我正在尝试像这样观察 collectionView.contentSize :

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 ,如下所示:

Optional(["old": NSSize: {320, 0}, "new": NSSize: {375, 39.5}, "kind": 1])

在 objective-c 中我使用了方法 CGSizeValue

CGSize newContentSize = [[change objectForKey:NSKeyValueChangeNewKey] CGSizeValue];

swift中有没有类似CGSizeValue的方法

我在 swift 中尝试过 var newContentSize = change[NSKeyValueChangeNewKey]?.CGSizeValue() 但出现错误

could not find member 'CGSizeValue'

需要帮助吗?谢谢

最佳答案

使用 Swift 4,您可以将键 NSKeyValueChangeKey.newKeychange 字典的结果转换为 CGSize 类型:

if let size = change?[NSKeyValueChangeKey.newKey] as? CGSize {
/* ... */
}

下面的 UIViewController 实现展示了如何设置一个 KVO 堆栈,以便观察任何 UIScrollView 子类的 contentSize 属性的变化(例如 UITextView):

import UIKit

private var myContext = 0

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!

/* ... */

override func viewDidLoad() {
super.viewDidLoad()

textView.addObserver(self, forKeyPath: #keyPath(UITextView.contentSize), options: [NSKeyValueObservingOptions.new], context: &myContext)
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext,
keyPath == #keyPath(UITextView.contentSize),
let contentSize = change?[NSKeyValueChangeKey.newKey] as? CGSize {
print("contentSize:", contentSize)
}
}

deinit {
textView.removeObserver(self, forKeyPath: #keyPath(UITextView.contentSize))
}

}

请注意,在 Swift 4 中,作为 addObserver(_:, forKeyPath:, options:, context:)observeValue(forKeyPath:, of:, change:, context :),您可以使用 observe(_:, options:, changeHandler:) 来跟踪您的 UIScrollView 子类 contentSize属性变化:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!
var observer: NSKeyValueObservation?

/* ... */

override func viewDidLoad() {
super.viewDidLoad()

let handler = { (textView: UITextView, change: NSKeyValueObservedChange<CGSize>) in
if let contentSize = change.newValue {
print("contentSize:", contentSize)
}
}
observer = textView.observe(\UITextView.contentSize, options: [NSKeyValueObservingOptions.new], changeHandler: handler)
}

}

关于xcode - swift 使用 KVO 观察 contentSize (CGSize),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31421387/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com