2

I have a NSView from which I need to be noticed if the frame changed.

class CustomView: NSView {

    override var frame: NSRect {

        didSet {
            Swift.print("changed frame: \(self.frame)")
        }
    }
}

But I only get this "notifikation" if the superView frame is resized.

If I do something like this inside the NSView class:

NotificationCenter.default.addObserver(forName:  Notification.Name(rawValue: "changeOwnSize"), object: nil, queue: nil) { notification in

          let newSize = NSSize(width: self.frame.width / 2, height: self.frame.height)
          self.setFrameSize(newSize)
}

The didSet function doesn´t react at all. Although the frame size is changed. Thanks for any advice.

Josch Hazard
  • 323
  • 3
  • 20

1 Answers1

13

Two steps:

  1. At some point, set your view's postsFrameChangedNotifications property to true.

  2. At this point, you should be able to observe the view's frameDidChangeNotification using NSNotificationCenter (if using Swift 3, it's NSNotification.Name.NSViewFrameDidChange or something similar).

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
  • Does that work for iOS `UIView`s? The docs only show it supported for `NSView` in Mac OS. – Duncan C Aug 29 '17 at 17:37
  • I don't see any reference to a notification in the docs, so I'd assume probably not. It seems intuitive that an iOS `UIView` would be much less likely to have its frame changed without your program code having been behind it. – Charles Srstka Aug 29 '17 at 17:39
  • iOS seems to rely on things like KVO and notifications a lot less than Mac OS, I think because they are rather "heavyweight" and require both more memory and more CPU horsepower. My guess is that Apple decided to drop that feature when they were implementing iOS views. – Duncan C Aug 29 '17 at 20:40
  • Works great. Took a while till i found out that the notified object is the whole NSView, not only NSRect. Thanks! – Josch Hazard Aug 29 '17 at 21:21
  • 1
    In XCode 11 (Swift 5), the notification name is `NSView.frameDidChangeNotification` – jsbox Nov 16 '20 at 01:36