1
我有一個MorphView.h文件,它跟蹤MorphView對象上手指的位置。iOS中的值觀察
#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];
的init和也做了觀測所需的功能。
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"morphX"])
{
NSLog(@"Success in observation!");
}
}
但是,我沒有看到「成功觀察」正在打印。我做錯了嗎?我想要的只是從我的主視圖控制器跟蹤我的morphX值。
謝謝!
嗨,對不起,我真的開始與morphX那裏,並改變它,因爲它不工作。當MorphView.morphX更改爲morphX時仍然不起作用。編輯。 – lppier
查看我的更新。你設置了錯誤的觀察者。 – rmaddy
嗯,它仍然無法正常工作。我需要在MorphView中專門做什麼嗎?目前我只是在做_morphX = location.x;在touchesBegan – lppier