0

I have a view and I added a observer like this:

_aView = [UIView new];
[_aView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
_aView.frame = CGRectMake(100, 100, 100, 100);

In the observer method I get the new value :

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"frame"]) {
            NSLog(@"%@", change[@"new"]);
    }
  }

The log is NSRect: {{100, 100}, {100, 100}}. The question is that I got the value type is NSRect, how to convert it to CGRect?

In the UIKit library have no type named NSRect

Cong Tran
  • 1,448
  • 14
  • 30
ZeroChow
  • 422
  • 2
  • 5
  • 16

2 Answers2

2

Convert NSRect to CGRect by:

CGRect NSRectToCGRect(NSRect nsrect);

Note: NSRect doesn't exist in iOS, the above works in only in OSX.

For iOS: CGRect rect = [change[@"new"] CGRectValue]; //copied from Rob's answer

Read Rect Conversion in iOS.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
2

NSRect and CGRect are the same on OS X. You will find this in NSGeometry.h in the OS X SDK:

typedef CGRect NSRect;

On iOS, NSRect doesn't exist, but the formatting function is the same on both platforms and it prints NSRect regardless. You can get the CGRect value like this:

CGRect rect = [change[@"new"] CGRectValue];
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks for correcting me, my answer is not correct, but got +1. I was not aware that NSRectToCGRect is missing in iOS – Anoop Vaidya Dec 30 '15 at 07:55