动态创建单选按钮
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;
}
以上是关于动态创建单选按钮的主要内容,如果未能解决你的问题,请参考以下文章