Nasir
Nasir

Reputation: 431

how to call method by a button which is created through coding

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];

Upvotes: 0

Views: 1532

Answers (5)

Chirag Dj
Chirag Dj

Reputation: 630

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

Upvotes: 0

Lithu T.V
Lithu T.V

Reputation: 20021

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

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

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.

Upvotes: 0

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

- (void)buttonClicked: (UIButton *)sender
{
 // do stuff
}

Upvotes: 0

Pratik T
Pratik T

Reputation: 1597

- (void)buttonClicked:(id)sender
{
   // your code
}

Upvotes: 1

Related Questions