我能够在我的数组中为我的UIButton添加一个“setbackgroundimage”。现在所有按钮都具有相同的图像。如何创建一个switch语句,以便能够在我的NSarray中为每个initwithobjects @“”设置不同的图像?
以下是我正在使用的代码:
menuItems = [[NSArray alloc]initWithObjects:@"",@"",@"",@"",@"",@"",@"", nil];
for (int b=0;b<[menuItems count];b++) {
UIButton *mybutton = [[UIButton alloc]initWithFrame:CGRectMake(3.0f, originofButtons, buttonWidth, buttonHeight)];
//mybutton.backgroundColor = [UIColor redColor];
[mybutton setBackgroundImage:[UIImage imageNamed:@"menubutton.png"]
forState:UIControlStateNormal];
[mybutton setTag:b];
[mybutton setTitle:[menuItems objectAtIndex:b] forState:UIControlStateNormal];
[mybutton setSelected:false];
[mybutton addTarget:self action:@selector(buttonpress:) forControlEvents:UIControlEventTouchUpInside];
[m_scrollview addSubview:mybutton];
originofButtons += (buttonHeight + buttonseparator);
}
答案 0 :(得分:1)
设置所选图像:
[mybutton setBackgroundImage:[UIImage imageNamed:@"YOUR_SELECTED_IMG.png"] forState:UIControlStateSelected];
虽然您希望各自设置不同,但您可以链接tag
。
switch (myButton.tag) {
case 0:
[mybutton setBackgroundImage:[UIImage imageNamed:@"YOUR_SELECTED_IMG.png"] forState:UIControlStateSelected];
break;
case 1:
[mybutton setBackgroundImage:[UIImage imageNamed:@"YOUR_SELECTED_IMG.png"] forState:UIControlStateSelected];
break;
}
答案 1 :(得分:0)
这可以帮助您完成您的方案。 您可以在NSArray中添加按钮图像名称,然后使用以下代码片段为每个案例设置图像:
NSArray* menuItems = [[NSArray alloc]initWithObjects:@"FirstScreen",@"SecondScreen",@"ThridScreen", nil];
for (int b=0;b<[menuItems count];b++) {
UIButton *mybutton = [[UIButton alloc]init ];//WithFrame:CGRectMake(3.0f, originofButtons, buttonWidth, buttonHeight)];
[mybutton setBackgroundImage:[UIImage imageNamed:[menuItems[b] stringByAppendingString:@".png"]] forState:UIControlStateSelected];
答案 2 :(得分:0)
我希望根据您的要求,这对您有所帮助......
menuItems = [[NSArray alloc]initWithObjects:@"",@"",@"",@"",@"",@"",@"", nil];
for (int b=0;b<[menuItems count];b++) {
UIButton *mybutton = [[UIButton alloc]initWithFrame:CGRectMake(3.0f, originofButtons, buttonWidth, buttonHeight)];
//mybutton.backgroundColor = [UIColor redColor];
[mybutton setBackgroundImage:[self getImageFromIndex:b %4]
forState:UIControlStateNormal];
[mybutton setTag:b];
[mybutton setTitle:[menuItems objectAtIndex:b] forState:UIControlStateNormal];
[mybutton setSelected:false];
[mybutton addTarget:self action:@selector(buttonpress:) forControlEvents:UIControlEventTouchUpInside];
[m_scrollview addSubview:mybutton];
originofButtons += (buttonHeight + buttonseparator);
}
-(UIImage *) getImageFromIndex:(short) index
{
switch (index) {
case 0:
return [UIImage imageNamed:@"card_01.png"];
break;
case 1:
return [UIImage imageNamed:@"card_02.png"];
break;
case 2:
return [UIImage imageNamed:@"card_03.png"];
break;
case 3:
return [UIImage imageNamed:@"card_04.png"];
break;
default:
return [UIImage imageNamed:@"card_01.png"];
break;
}
return nil;
}