如何使用带参数的事件处理程序?
Posted
技术标签:
【中文标题】如何使用带参数的事件处理程序?【英文标题】:How do you use event handlers with parameters? 【发布时间】:2010-10-08 05:53:58 【问题描述】:我正试图弄清楚这些事件是如何运作的。在 iTunes U 上斯坦福课程的视频 4 中,Alan Cannistraro 说有
“三种不同风格的动作方法选择器类型 - (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
标记
【问题讨论】:
【参考方案1】:很老的问题,我知道...
我刚刚测试过:
- (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)
所以它只是工作。问题出在其他地方。
【讨论】:
以上是关于如何使用带参数的事件处理程序?的主要内容,如果未能解决你的问题,请参考以下文章
如何将 JComboBox 事件处理程序的字符串放入变量中进行查询?