触摸按钮时如何更改UIButton图像

时间:2013-01-08 11:02:34

标签: objective-c ios uibutton uicontrol

我试图在触摸按钮时更改UIButton图像。目前我改变了但仅限于突出显示的状态变化。我希望它改变并留在那里。我尝试了UIControlStateSelected进行状态更改,但没有运气。

感谢您的帮助

这是我的代码:

 // Create buttons for the sliding category menu.
    NSMutableArray* buttonArray = [NSMutableArray array];
    NSArray * myImages = [NSArray arrayWithObjects:@"category-cafe-unsel.png", @"category-food-unsel.png", @"category-clothing-unsel.png", @"category-health-unsel.png", @"category-tech-unsel_phone.png" , @"category-tech2-unsel.png", @"catefory-theatre-unsel.png", @"category-travel-unsel.png", nil];

    NSArray * myImagesSel = [NSArray arrayWithObjects:@"category-cafe-sel.png", @"category-food-sel.png", @"category-clothing-sel.png", @"category-health-sel.png", @"category-tech-sel_phone.png" , @"category-tech2-sel.png", @"catefory-theatre-sel.png", @"category-travel-sel.png", nil];

    // only create the amount of buttons based on the image array count
    for(int i = 0;i < [myImages count]; i++)
    {
        // Custom UIButton

        btn = [UIButton buttonWithType:UIButtonTypeCustom];

        [btn setFrame:CGRectMake(0.0f, 20.0f, 52.0f, 52.0f)];
        [btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:i]] forState:UIControlStateHighlighted];

        NSLog(@"The button title is %@ ", btn.titleLabel.text);

        [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [buttonArray addObject:btn];

2 个答案:

答案 0 :(得分:2)

在您的IBAction方法中添加以下行:

 - (IBAction)change:(id)sender
 {
   UIButton *button = (UIButton *)sender;
   int tagOfButton = button.tag - 1;
   [button setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:tagOfButton]] forState:UIControlStateNormal];
 }

在for循环中添加一行,如:

for(int i = 0;i < [myImages count]; i++)
{
    // other stuffs
    btn.tag  = i+1;
}

修改

如果您在单击其他按钮时需要撤消上一个选择:

在IBAction方法中写下这个循环。

for(int i = 0;i < [myImages count]; i++)
{
  UIButton *but = (UIButton *)[buttonArray objectAtIndex:i];
  if(but != button)
  {
       [btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
  }
}

或者只是将前一个按钮标记存储到变量中。 并用它来改变图像的变化。

答案 1 :(得分:0)

[btn setTitle:@"I'm not selected" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:[myImages objectAtIndex:i]] forState:UIControlStateNormal];
[btn setTitle:@"I'm selected" forState:UIControlStateSelected];
[btn setImage:[UIImage imageNamed:[myImagesSel objectAtIndex:i]] forState:UIControlStateSelected];

[btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

-(IBAction)buttonPressed:(id)sender {
  btn.selected = !btn.selected;
}