1

我有一个 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 值。

谢谢!

4

1 回答 1

1

您为 的关键路径添加了一个观察者morphX,而不是MorphView.morphX。更改观察者以与正确的路径进行比较。

if([keyPath isEqualToString:@"morphX"])

如果您想确保这来自特定对象,则将object参数与维护对该对象的引用的某个实例变量进行比较。

此外,您将错误的观察者传递给addObserver.... 它应该是:

[morphPadBtn addObserver:self forKeyPath:@"morphX" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

观察者需要是实现该observeValueForKeyPath:...方法的类。

于 2013-08-30T03:17:27.550 回答