动态创建单选按钮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态创建单选按钮相关的知识,希望对你有一定的参考价值。

我想从数组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;
}

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

答案
-(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;
}

以上是关于动态创建单选按钮的主要内容,如果未能解决你的问题,请参考以下文章

动态创建“ul”和“li”并配置“单选按钮”的错误消息

单选按钮在动态创建的 RadioGroup 中没有正确选择/取消选择

动态单选按钮单选组和视图不起作用

动态创建单选按钮

单选按钮以片段形式传递数据

MFC 在代码中增加单选按钮