我有一个 MorphView.h 文件,它在其中跟踪手指在 MorphView 对象上的位置。
#import <UIKit/UIKit.h>
@interface MorphView : UIButton
@property (nonatomic) float morphX;
@property (nonatomic) float morphY;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event ;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
@end
我想从我的主视图控制器“观察”按钮的 morphX。我阅读了关键值观察并做到了这一点。
在 ViewController.m 的初始化中
MorphView* morphPadBtn = [MorphView buttonWithType:UIButtonTypeCustom];
[morphPadBtn addTarget:self action:@selector(morphPressedDown:withEvent:) forControlEvents:UIControlEventTouchDown];
UIImage *buttonbkImage = [UIImage imageNamed:@"buttonback"];
[morphPadBtn setBackgroundImage:buttonbkImage forState:UIControlStateNormal];
[morphPadBtn setAdjustsImageWhenHighlighted:NO];
morphPadBtn.frame = CGRectMake(300, 200, 300, 300.0);
[self.view addSubview:morphPadBtn];
[morphPadBtn addObserver:morphPadBtn forKeyPath:@"morphX" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
并且还做了观察所需的功能。
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"morphX"])
{
NSLog(@"Success in observation!");
}
}
但是,我没有看到“观察成功”被打印出来。我做错了吗?我想要的只是从我的主视图控制器跟踪我的 morphX 值。
谢谢!