动态创建单选按钮

时间:2018-01-03 08:29:11

标签: ios objective-c radio-button

我想从数组count创建一个动态单选按钮。如果我选​​择任何一个单选按钮,其他单选按钮应该取消选择状态。 请帮我这样做。

   for (int f = 0; f<self.arr.count; f++) {

        UILabel *lbl = [[UILabel alloc]init];
             lbl.frame = CGRectMake(20,radio_y+10 , 30, 20);

             lbl.text = self.arr[f];
             lbl.textColor = [UIColor blackColor];


             [RadioView addSubview:lbl];

          self.yourButton = [[UIButton alloc] initWithFrame:CGRectMake(5,radio_y+5 , 10, 10)];
             [self.yourButton setImage: [UIImage imageNamed:@"RadioButton-Selected.png"]forState:UIControlStateNormal];
             [self.yourButton setImage: [UIImage imageNamed:@"RadioButton-Unselected.png"]forState: UIControlStateNormal];
             self.yourButton.selected = NO;

               [self.yourButton addTarget:self action:@selector(radioSelected:) forControlEvents:UIControlEventTouchUpInside];
             [self.yourButton setTag:baseradioTag+f];

             NSLog(@"%ld",(long)self.yourButton.tag);

             [RadioView addSubview:self.yourButton];

             radio_y = radio_y +(verticalPadding+5);
                          }
  -(void)radioSelected:(UIButton*)sender {

int tag =sender.tag;
NSLog(@"buttonSelectedtag:%d",tag);

sender.selected = !sender.selected;
self.yourButton = sender;
}

我确实喜欢这个,但如果我触摸按钮,按钮就不会改变为所选图像。

1 个答案:

答案 0 :(得分:0)

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

     int tag =sender.tag;
     NSLog(@"buttonSelectedtag:%d",tag);

     sender.selected = !sender.selected;
     self.yourButton = sender;

     for (UIButton *i in self.view.subviews){
          if([i isKindOfClass:[UIButton class]]){
              UIButton *btn = (UIButton *)i;
              if(btn.tag == previouslySelectedTag){ //hold previouslySelectedTag, selectedTag globally 
                // Write your code. Change Button Image
              }
          }
      }
      previouslySelectedTag = sender.tag;
}