在ObjC
static void * const kKVOContext = (void*)&kKVOContext;
[self.superview removeObserver:self.parent forKeyPath:NSStringFromSelector(@selector(contentOffset)) context:kKVOContext];
contentOffset
是 UIScrollView
属性。
我已经把它写成 swift as-
swift
var kKVOContext = UnsafeMutableRawPointer.allocate(bytes: 4 * 4, alignedTo: 1)
self.superview?.removeObserver(self.parent!, forKeyPath: NSStringFromSelector(#selector(getter: UIScrollView.contentOffset)), context: &kKVOContext)
所以在 Swift 中
这是正确的方法还是应该是不同的 UnsafeMutableRawPointer
?或如何快速编写 kKVOContext
?
最佳答案
你可以使用 swift 4 的新特性
// Setting up KVO
observation = scrollView.observe(\.contentOffset, changeHandler: { (object, change) in
print("Updated Value: \(object.contentOffset)")
})
// Deiniting or invalidating the observation token ends the observation
observation.invalidate()
// After invalidating KVO doesn't trigger anymore
关于ios - 在 Swift 中编写 Kvo 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47504193/