我有一個ViewController和一個UIView,並希望在類型CGRect的UIView屬性上執行KVO。由於某種原因,它不能按照應有的方式工作。 我的代碼如下所示:對我iOS5 UIView CGRect屬性KVO無法正常工作
@interface MyView : UIView
@property (nonatomic, assign) CGRect myRect;
@end
@implementation MyView
@synthesize myRect;
...
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
...
//Changing structures values
myRect.origin.x+=moveVector.x;
myRect.origin.y+=moveVector.y;
//assigning new structure
[self setMyRect:CGRectMake(20, 20, 50, 50)];
//Both doesn't call
}
我想用我的viewController觀察的CGRect。不知道我應該在這裏與MVC有多嚴格。順便說一句,在MyView CGRect只是一個可見的廣場,我可以移動,所以我會說它不是一個模型,應該留在MyView。如果我錯了,請糾正。
這裏是我的ViewController:
@class MyView;
@interface MyViewController : UIViewController
@property (nonatomic, retain) MyView *overlayView;
@end
@implementation MyViewController
@synthesize overlayView;
- (void)viewDidLoad
{
[super viewDidLoad];
overlayView = [[CameraOverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[overlayView addObserver:self
forKeyPath:@"myRect"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
/* [self addObserver:self
forKeyPath:@"overlayView.myRect"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];*/
self.view = overlayView;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void*)context {
if([keyPath isEqualToString:@"myRect"]) {
NSLog(@"observeValueForKeyPath");
CGRect rect = [[change valueForKey:NSKeyValueChangeNewKey] CGRectValue];
}
}
observeValueForKeyPath不會被調用,不管我如何在MyView的改變myRect。 setMyRect:在運行時崩潰,我真的不知道爲什麼。我雖然綜合將照顧setter和getters以及keyvalues和變化。 Iam也不確定addObserver的哪種方式:更好的方法,因爲我註釋了我第二次嘗試註冊Observer。
iam做錯了什麼?觀察結構不可能嗎?或者只有自己寫的setter和getter? 它可以是UIView不符合KVC,如果是的話,爲什麼這個工作? Callback by KVO on a UIView frame property 感謝您的幫助:-)