当我们点击按钮时如何更改图像?

时间:2017-08-02 05:35:47

标签: 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;

    }

这是&#34; self.radioBtnTagArr&#34;来自服务器(标签来自服务器),基于该计数我想创建单选按钮,并且我将标签分配给单选按钮。

- (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

我想只在点击第一个按钮第一个按钮状态被选中的时候,如果点击这样选择的第二个按钮第二个按钮状态...

1 个答案:

答案 0 :(得分:1)

要创建另一个数组以保存UI按钮,例如

<强>步骤1

@property (nonatomic, strong)  NSMutableArray *buttonArray;

<强>步骤-2

将所有按钮添加到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];

    }

<强>步骤-3

在目标

 - (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];

}