从数组中我创建的按钮与数组值在每个按钮,这里我想在每个按钮之前放置一个单选按钮。在点击单选按钮时,我想让它被选中或不选中。在下面的代码中,我可以显示按钮和单选按钮图像,但无法获得选中的按钮值。我怎么能得到单选按钮选中或不为每个按钮
//My Array
labelArrays = [NSMutableArray arrayWithObjects:@"one", @"two", @"three",@"four",@"five",@"six", nil];
//Creating button with placing a radio button image inside
-(void) createbutton:(CGRect) frame {
CGFloat xCoordinate = frame.origin.x;
CGFloat yCoordinate = frame.origin.y;
CGFloat buttonHeight = frame.size.height;
CGFloat buttonWidth = frame.size.width;
CGFloat gapBetweenTwoButton = 2;
for(int counter = 0; counter < [labelArrays count]; counter++) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button =[UIColor clearcolor];
[button setFrame:CGRectMake(xCoordinate,yCoordinate, 100, 40)];
NSString* titre = [labelArrays objectAtIndex:counter];
[button setImage:[UIImage imageNamed:@"radio_selected.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(0,10,0,0);
[button setTitle:[NSString stringWithFormat:@"%@",titre] forState:UIControlStateNormal];
[button setUserInteractionEnabled:YES];
[self. button addTarget: self action: @selector(buttonAction:)forControlEvents: UIControlEventTouchUpInside];
[self addSubview: button];
if((counter+1)%3 == 0) {
xCoordinate = 0;
yCoordinate = yCoordinate + buttonHeight + gapBetweenTwobutton;
xCoordinate = xCoordinate + buttonWidth + gapBetweenTwoLabels;
}
}
//my frame
[self createbutton:CGRectMake(32,20,220,40)];
通过使用其标记值来获取所选按钮值非常简单。查看这里并尝试下面的代码。
将这些行放入viewDidLoad()
labelArrays = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", @"four", @"five", @"six", nil];
[self createButtons];
然后定义这些方法。
- (void)createButtons
{
int x = 30, y = 20;
for (int i = 0; i<labelArrays.count; i++)
{
UIButton *btnImage = [UIButton buttonWithType:UIButtonTypeCustom];
btnImage.frame = CGRectMake(x, y, 100, 40);
btnImage.backgroundColor = [UIColor redColor];
btnImage.tag = 700+i;
[btnImage setImage:[UIImage imageNamed:@"radio_unselect.png"] forState:UIControlStateNormal];
btnImage.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
[btnImage setTitle:[NSString stringWithFormat:@"%@", [labelArrays objectAtIndex:i]] forState:UIControlStateNormal];
[btnImage addTarget: self action: @selector(changeValue:)forControlEvents: UIControlEventTouchUpInside];
[self.view addSubview:btnImage];
if ((i+1)%2 == 0)
{
x = 30;
y = y+btnImage.frame.size.height+10;
}
else
{
x = x+btnImage.frame.size.width+30;
}
}
}
- (IBAction)changeValue:(UIButton *)sender
{
UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag];
if (btn.selected == TRUE)
{
[btn setImage:[UIImage imageNamed:@"radio_unselect.png"] forState:UIControlStateNormal];
btn.selected = FALSE;
}
else
{
[btn setImage:[UIImage imageNamed:@"radio_select.png"] forState:UIControlStateNormal];
btn.selected = TRUE;
NSLog(@"%@", btn.titleLabel.text);
}
}