如何更改按钮的图像

时间:2012-07-05 05:09:51

标签: iphone objective-c ios5 uiview uibutton

我正在使用此代码在滚动视图中显示图像...在此按钮中使用for循环创建...然后为每个按钮设置图像...现在我想选择多个图像..我希望当我点击特定按钮时,其图像替换为“勾选图像”,当我再次按下它时,替换为原始图像意味着显示未选中..

for(int i=0; i<[imageArray count]; i++)
{
  if((i%4) == 0 && i!=0)
  {
      horizontal = 8.0;
      vertical = vertical + 70.0 + 8.0;
  }

  buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
  [buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
  [buttonImage setTag:i];
  [buttonImage setImage:[arrayOfImages objectAtIndex:i] forState:UIControlStateNormal];
  [buttonImage addTarget:self action:@selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
  [myScrollView addSubview:buttonImage];

  horizontal = horizontal + 70.0 + 8.0;
}

我尝试使用此代码在(buttonImagePressed)方法中更改了状态更改...

[buttonImage setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateSelected];

但它不起作用......它每次只更改最后一个按钮的图像而不是特定的点击按钮....我也试图隐藏按钮但它再次隐藏最后一个按钮。在哪里我做错了???

还有其他方法可以改变吗???请帮帮我

2 个答案:

答案 0 :(得分:4)

而不是UIControlStateSelected你应该使用UIControlStateNormal并保留一些bool值来显示该按钮之前是否被选中,或者你可以根据选择说明将button的selected属性设置为true或false:

-(void) buttonImagePressed:(UIButton*)sender
{
   UIButton *button = sender;
  if(button.selected) //already selected so now it should be deselected
  {
     [button setImage:[UIImage imageNamed:@"UnCheckmark.png"] forState:UIControlStateNormal];
      button.selected = false;
  }
   else
   { 
      [button setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateNormal];
      button.selected = true;
   }

}

答案 1 :(得分:1)

为此,将全局标志变量设为BOOL Flag = NO;

也为每个按钮设置标记。

方法

-(IBAction)buttonImagePressed:(UIButton *)sender{
 if(flag==NO){
   flag=YES;
   [sender setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateNormal];
  }
 else{
 flag=NO;
 [sender setImage:[arrayOfImages objectAtIndex:sender.tag] forState:UIControlStateNormal];
 }
}