Reputation: 77
I have create some buttons on for loop on below code.
UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)];
[buttonsView setBackgroundColor:[UIColor greenColor]];
for (int i = 0; i < myObject.count; i ++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(35*i + 5, 0, 35, 35)];
[button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal];
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
[buttonsView addSubview:button];
}
And now, How to I can click button to handle event.
Every button was clicked, It will handle 1 event.
Ex: if I have 2 buttons was created by for loop. When I click button 1, it's will log 1, When I click button 2, it's will log 2.
Upvotes: 0
Views: 189
Reputation: 82759
do like
UIView *buttonsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _viewEmoji.frame.size.width, 35)];
[buttonsView setBackgroundColor:[UIColor greenColor]];
for (int i = 0; i < myObject.count; i ++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(35*i + 5, 0, 35, 35)];
[button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [myObject objectAtIndex:i]]] forState:UIControlStateNormal];
[button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
// set the tag for identify which button you pressed
button.tag = i; // else use --> [myObject objectAtIndex:i]
[buttonsView addSubview:button];
}
//here add your buttonsView to mainview
self.view addsubview(buttonsView)
// for button action
-(void)clickButton:(UIButton*)sender
{
NSLog(@" Index: %d ", sender.tag);
[sender setBackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal];
}
Upvotes: 1