2011-12-01 3 views
8

Sono nuovo alla tecnologia iPhone. Per favore qualcuno mi dica come aggiungere un'azione per UIButton.Come aggiungere un'azione per UIButton

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btn.frame = CGRectMake(0, 0, 100, 25); 
btn.backgroundColor = [UIColor clearColor]; 
[btn setTitle:@"Play" forState:UIControlStateNormal]; 
[btn addTarget:self action:(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; 
btn.center = self.center; 
[self addSubview:btn]; 
+0

Non sulla questione, ma si ha una perdita di memoria qui. non chiamare mantenere sul pulsante se non si chiama più tardi. Il retain non è necessario in quanto il pulsante non è un ivar ed è autoreleased. – Zoleas

+0

Rimossa la perdita di memoria. –

risposta

7

possibile specificare selettori utilizzando @selector(). Così, il parametro azione sembra,

action:@selector(buttonClick:) 
1
action:@selector(buttonClick:) 
7

Usa questa

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [button addTarget:self 
     action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown]; 
    [button setTitle:@"Show View" forState:UIControlStateNormal]; 
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); 
    [view addSubview:button]; 
0

Swift code:

button.addTarget(self, action:"action_button", forControlEvents:.TouchUpInside) 
... 
func action_button() { 
    // implement me 
} 
1

Usa Like This

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     btn.frame = CGRectMake(0, 0, 100, 25); 
     btn.backgroundColor = [UIColor clearColor]; 
     [btn setTitle:@"Play" forState:UIControlStateNormal]; 
     [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside]; 
     btn.center = self.center; 
[self addSubview:btn]; 

e aggiungere il tuo metodo di selezione

-(IBAction)btnTapped:(id)sender{ 

}