【问题标题】:how to change multiple button image and conditions如何更改多个按钮图像和条件
【发布时间】:2015-03-03 05:53:38
【问题描述】:

我在表视图单元中有两个按钮,当我单击第1个按钮时,背景图像更改为所选图像,同时我的第2张按钮图像不应改变第1按钮时。我该怎么做这个过程。

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = CGRectMake(80, 27, 36, 36);
[button1 setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"l"ofType:@"png"]] forState:UIControlStateNormal];
 button1.tag = 1;
[button1 addTarget:self action:@selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button1];

  UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button2.frame = CGRectMake(160, 27, 36, 36);
[button2 setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"e"ofType:@"png"]] forState:UIControlStateNormal];
   button2.tag = 2;
[button2 addTarget:self action:@selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button2];


- (void)radiobtn:(UIButton *)button
{

}

这些按钮在表格视图单元格中,第一个按钮选择的图像名称 = 蓝色图像。 第二个按钮选择的图像名称 = 红色图像。请帮助我,我是 IOS 新手。

【问题讨论】:

  • 对 2 个按钮使用不同的按钮操作方法。您正在使用相同的按钮操作。在第一个按钮操作中更改 btn1 的背景图像。
  • @RJV 你能帮我写代码吗

标签: ios objective-c uitableview uiimageview uibutton


【解决方案1】:

请使用不同的选择器并在不同的函数中执行代码。现在你只使用了一个方法,即radiobtn:(UIButton *){}

或者,如果您想保留相同的选择器,则可以检查单击哪个按钮的标签并相应地执行代码

-(void)radiobtn:(UIButton *)button
{
     if(button.tag==1)
    {
    // perform the code when button 1 is clicked and change the images accordingly
    }
    else
    {
    // perform the code when button 2 is clicked 
    }
}

【讨论】:

  • if ([button1 isSelected]) { [button setImage:[UIImage imageNamed:@"l.png"] forState:UIControlStateNormal]; NSLog(@"选择"); [button1 setSelected:NO]; } else { [button setImage:[UIImage imageNamed:@"lblue.png"] forState:UIControlStateSelected]; NSLog(@"不选择"); [button1 setSelected:YES];我试过这个按钮 1 图像没有改变为什么?
  • 代替 setImage 使用 setBackgroundImage..因为你有使用 isSelected
  • 不使用被选中。只需使用按钮的标签
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
相关资源
最近更新 更多