0

i am fresh in iphone..i have created one button and through coding and want to call a method by that button what should i do please help me..

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(20, 20, 150, 44); // position in the parent view and set the size of the button
[myButton setTitle:@"Click Me!" forState:UIControlStateNormal];
// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
// add to a view
[myview addSubview:myButton];
Nasir
  • 421
  • 7
  • 21
  • Just a quick comment. This is iOS, on an iPhone. There is no "clicking" of buttons. Although it makes no difference I'd prefer to use `buttonTapped`. "Click" has no relevance to iOS. – Fogmeister Jun 10 '13 at 08:24

5 Answers5

2

The answer is in the question itself

// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

this line added a action to the button which is in self with action name buttonClicked: for the controlevent touchUpInside

so when a button is touchupInside it will execute the method buttonClicked

Therefore

- (void)buttonClicked: (UIButton *)sender
{
 // do whatever you want to do here on button click event
}

will get executed on button action

Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
1
- (void)buttonClicked:(id)sender
{
   // your code
}
Pratik B
  • 1,599
  • 1
  • 15
  • 32
0
- (void)buttonClicked: (UIButton *)sender
{
 // do stuff
}
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
0

Take a look at UIControl documentation

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents  

action : A selector identifying an action message. It cannot be NULL.

You are passing @selector(buttonClicked:) as action. @selector() is a compiler directive to turn whatever's inside the parenthesis into a SEL. A SEL is a type to indicate a method name, but not the method implementation.[1] so implement -(void)buttonClicked:(id)sender in your class.

Community
  • 1
  • 1
Parag Bafna
  • 22,812
  • 8
  • 71
  • 144
0
- (void)buttonClicked: (UIButton *)sender
{
 // do whatever you want to do here on button click event
}
Chirag Dj
  • 630
  • 2
  • 9
  • 27