ios - 单击按钮时如何更改图像?

标签 ios objective-c uibutton radio-button

我正在使用单选按钮,为此我正在编写这样的代码。

float x = 40;
float y = 0;
for (int i=0; i<self.radioBtnTagArr.count; i++) {

        self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0);
        [self.radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal];
        [self.radioButton addTarget:self action:@selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:self.radioButton];
        self.radioButton.tag = [[self.radioBtnTagArr objectAtIndex:i] intValue];

        y = y+70;

    }

这个“self.radioBtnTagArr”来自服务器(标签来自服务器),根据该计数,我想创建单选按钮,并将该标签分配给单选按钮。

- (void) radioBtnMethod:(UIButton *)sender {

for (int i=0; i<self.radioBtnTagArr.count; i++) {

    if (sender.tag == [[self.radioBtnTagArr objectAtIndex:i] intValue]) {

        [self.radioButton setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateSelected];

        [self.radioButton setSelected:YES];

    }

}
}

现在的问题是,当我单击第一个单选按钮时,最后一个单选按钮被选中,如下图所示...

Radio button image

我只想当我们单击第一个按钮时选择第一个按钮状态,如果我们单击第二个按钮则选择第二个按钮状态,如下所示...

最佳答案

喜欢创建另一个数组来保存 UIbutton,例如

第一步

@property (nonatomic, strong)  NSMutableArray *buttonArray;

第二步

将所有按钮添加到buttonArray

   // allocate the memory for your array
  buttonArray = [NSMutableArray array];

for (int i=0; i<self.radioBtnTagArr.count; i++) {
        // create instance value of UIButton
        UIButton *radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
         radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0);
        [radioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal];
        [radioButton addTarget:self action:@selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:self.radioButton];

        y = y+70;
       // add the object to array
       [buttonArray addObject:radioButton];

    }

第三步

目标内部

 - (void) radioBtnMethod:(UIButton *)sender {

  // reset the previous selection
  for (UIButton *getradioButton in buttonArray) {
       [getradioButton setImage:[UIImage imageNamed:@"radio_empty.png"] forState:UIControlStateNormal];
}
   // set the current selection
   [sender setImage:[UIImage imageNamed:@"radio.png"] forState:UIControlStateNormal];

}

关于ios - 单击按钮时如何更改图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45452253/

相关文章:

ios - Alamofire框架和iOS证书问题

ios - 如何在 SwiftUI 中正确设置辅助功能标识符?

ios - 如何检索Facebook好友群组名称?

iphone - NSPersistentStoreCoordinator 出现 nil 模型错误?

ios - 如何防止按钮高亮

ios - RESTKit:在没有映射类的情况下映射 JSON

objective-c - 如何动态添加列表到搜索字段?

ios - 在行的按钮附近添加一个 UIView?

ios - 快速在 UIView 子类中创建 subview

ios - 如何使 TabBarController 的 ViewController 上的 UIButton 使用户返回到 Swift 中最后选择的 TabBarViewController(不是当前的)