嗨,我是iphone的新手。我所做的是在视图中创建一组按钮。我的代码就像休闲一样
- (void)mymethod1 {
UIView *view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
int row = 0;
int column = 0;
for (int i=6; i<_images.count; i++) {
buttonimage = [UIButton buttonWithType:UIButtonTypeCustom];
buttonimage.frame = CGRectMake(column*60+5, row*60+5, 70,70);
[buttonimage setImage:[UIImage imageNamed:[_images objectAtIndex:i]] forState:UIControlStateNormal];
buttonimage.tag = i;
[buttonimage addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
buttonimage.tag = i;
[view addSubview:buttonimage];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
self.view = view;
[ view release];
}
它工作正常。但是当我调用任何其他功能中的所有按钮时,它只能获得最后一个按钮,例如:
- (void)mymethod2 {
NSLog(@"button value %d",buttonimage.tag);
}
“它进入控制台按钮值5”。但我需要获取mymethod2中的所有按钮标记值。如何获取所有按钮标签值。请发布一些代码。谢谢你提前。
答案 0 :(得分:6)
你需要迭代当前视图的所有子视图,然后在转换之前检查它是否是一个按钮,如下所示
for (UIView* view in [self.view subviews]) {
if([view isKindOfClass:[UIButton class]]){
UIButton *btn = (UIButton*)view;
NSLog(@"button value %d", btn.tag);
}
}
答案 1 :(得分:0)
所有按钮标记值: -
for(int i=0;i<3;i++){
UIButton *theButton=[[UIButton alloc]init];
theButton.tag=i;
//set their selector using add selector
[theButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchDown];
//set their frame color title or image
}
-(void)buttonClicked:(UIButton *)inButton{
int tags=inbutton.tag;
}
答案 2 :(得分:0)
UIButton *BtnTmp=sender;
if([BtnTmp tag])
[BtnTmp setImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
else
[BtnTmp setImage:[UIImage imageNamed:@"uncheck.png"] forState:UIControlStateNormal];
BtnTmp.tag=!BtnTmp.tag;