我在下面的代码上为循环创建了一些按钮。
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];
}现在,我可以点击按钮来处理事件。
每个按钮被点击,它将处理1个事件。
例:如果我有2个按钮是由for循环创建的。当我单击按钮1,它将日志1,当我单击按钮2,它将日志2。
发布于 2015-11-05 15:43:18
喜欢
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];
}https://stackoverflow.com/questions/33548622
复制相似问题