2010-10-08 71 views
4

我試圖理清這些事件是如何工作的。在上的iTunes U斯坦福當然視頻4,艾倫Cannistraro說,有你如何使用帶參數的事件處理程序?

「3種不同的操作方法選擇器類型 的口味 - (無效)actionMethod; - (無效)actionMethod:(ID)發送者; - (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

馬克

回答

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) 

所以它j ust工作。問題在別的地方。

相關問題