问题
Is there a better way to observe NSScrollView -> NSClipView frame/bounds change? This is Obj-C code translated to Swift:
public override init(frame frameRect: NSRect) {
self.contentView.postsFrameChangedNotifications = true;
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "frameDidChange:",
name: NSViewFrameDidChangeNotification,
object: self.contentView)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: NSViewFrameDidChangeNotification,
object: self.contentView)
}
It works, but I don't want to use NSNotificationCenter. I want to use frame property observation on NSClipView:
class MyClipView: NSClipView {
...
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.postsFrameChangedNotifications = true;
}
override var frame: CGRect {
didSet {
println("Did set frame")
}
}
}
But didSet is called only 2 times after initialisation and it's never called when enclosing NSScrollView is scrolled. Looks that Apple is using internal methods to change the frame without calling frame property?
The same stands for NSViewBoundsDidChangeNotification and bounds property.
回答1:
not every change to the frame variable has to happen through the property:
==> therefore the didSet doesn't 'catch' all
next to the method setFrame
(the setter for the frame)
there are also other ways: setFrameOrigin
and setFrameSize
and even setFrameRotation
same for bounds
来源:https://stackoverflow.com/questions/28465033/swift-nsscrollview-better-nsviewboundsdidchangenotification-observing