Model view controller iOS5中my UIView CGRect属性上的KVO不是';行不通
我有一个ViewController和一个UIView,希望对CGRect类型的UIView属性执行KVO。由于某种原因,它不能正常工作。 我的代码如下所示:Model view controller iOS5中my UIView CGRect属性上的KVO不是';行不通,model-view-controller,uiview,key-value-observing,cgrect,Model View Controller,Uiview,Key Value Observing,Cgrect,我有一个ViewController和一个UIView,希望对CGRect类型的UIView属性执行KVO。由于某种原因,它不能正常工作。 我的代码如下所示: @interface MyView : UIView @property (nonatomic, assign) CGRect myRect; @end @implementation MyView @synthesize myRect; ... - (void)touchesMoved:(NSSet *)touches withEve
@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];
}
}
无论我如何在MyView中更改myRect,都不会调用observeValueForKeyPath。
setMyRect:在运行时崩溃,我真的不知道为什么。我想我会处理setter和getter以及键值和更改。
我也不确定addObserver:哪种方式更好,因为我已经评论了我第二次注册Observer的尝试
我做错了什么?难道不能观察建筑物吗?还是只使用自编的setter和getter?
是否UIView不符合KVC,如果是,为什么这样做?
感谢您的帮助:-)我的解决方案是,我使用一名代表。 控制器是我查看的委托人,我认为它应该是这样的, 否则UIView将被视为KVC投诉