我正在尝试理清事件的运作方式。在关于iTunes U的斯坦福大学课程的视频4中,Alan Cannistraro说有
“3种不同风格的动作方法选择器类型 - (void)actionMethod; - (void)actionMethod:(id)sender; - (void)actionMethod:(id)sender withEvent:(UIEvent *)event;“
我以为我会用一个简单的添加程序来尝试它们 - 你输入2个数字,当你输入时,总和会在第三个UITextField中获得位置。我有一个没有参数签名的方法,它工作正常。当我使用sender参数将其更改为第二个时,代码将停止调用该方法。
这有效:
-(void) setSum {
float a1 = addend1.text.floatValue;
float a2 = addend2.text.floatValue;
float thesum = a1 + a2;
NSString * ssum = [NSString stringWithFormat:@"%g", thesum];
sum.text = ssum;
}
-(void)awakeFromNib {
SEL setSumMethod = @selector(setSum);
[addend1 addTarget: self action: setSumMethod forControlEvents: UIControlEventEditingChanged];
[addend2 addTarget: self action: setSumMethod forControlEvents: UIControlEventEditingChanged];
}// awakeFromNib
这会运行,但不会调用setSum:
-(void) setSum:(id) sender {
float a1 = addend1.text.floatValue;
float a2 = addend2.text.floatValue;
float thesum = a1 + a2;
NSString * ssum = [NSString stringWithFormat:@"%g", thesum];
sum.text = ssum;
}
-(void)awakeFromNib {
SEL setSumMethod = @selector(setSum:);
[addend1 addTarget: self action: setSumMethod forControlEvents: UIControlEventEditingChanged];
[addend2 addTarget: self action: setSumMethod forControlEvents: UIControlEventEditingChanged];
}// awakeFromNib
所以,问题是其他事件方法类型何时起作用?只有第一个似乎适用。
TIA
标记
答案 0 :(得分:2)
很老的问题,我知道......
我刚试过它:
- (void) onField
{
NSLog(@"onField");
}
- (void) onField:(id) sender
{
NSLog(@"onField: %@", sender);
}
- (void) onField:(id) sender event:(id)event
{
NSLog(@"onField: %@\n%@", sender, event);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITextField *field = [[[UITextField alloc] initWithFrame:CGRectMake(0, 100, 100, 100)] autorelease];
[field setText:@"text"];
[field addTarget:self action:@selector(onField) forControlEvents:UIControlEventEditingChanged];
[field addTarget:self action:@selector(onField:) forControlEvents:UIControlEventEditingChanged];
[field addTarget:self action:@selector(onField:event:) forControlEvents:UIControlEventEditingChanged];
[window addSubview:field];
[window makeKeyAndVisible];
return YES;
}
结果:
2010-11-04 11:35:59.940 Untitled[599:207] onField
2010-11-04 11:35:59.941 Untitled[599:207] onField: <UITextField: 0x6a0c1f0; frame = (0 100; 100 100); text = 'textsfr'; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x6a0c350>>
2010-11-04 11:35:59.944 Untitled[599:207] onField: <UITextField: 0x6a0c1f0; frame = (0 100; 100 100); text = 'textsfr'; clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x6a0c350>>
(null)
所以它才有效。问题出在其他地方。