如何使按钮在IOS中具有单选按钮的功能

时间:2015-11-24 09:13:57

标签: ios

如果按下每个按钮,我有5个按钮,应该更改背景。如果我选择下一个按钮,则先前按下的按钮背景应更改为正常背景,并且应更改所选按钮背景(如单选按钮)。我怎样才能实现这一点,任何人都可以帮助我。

- (IBAction)butclaim2:(id)sender 
{ 
if ([sender isSelected]) 
 { 
  [butClaim2 setBackgroundImage:[UIImage imageNamed:@"i_radiobutton_full.png"] forState:UIControlStateHighlighted];
    [sender setSelected: NO]; 
  } 
  else 
   { 
    [sender setSelected: YES]; 
    } 
 } 

1 个答案:

答案 0 :(得分:0)

假设您的按钮是UIView的子视图,例如

步骤-1

创建一个全局NSMutableArray用于存储Button,例如

buttonsArray = [[NSMutableArray alloc] initWithCapacity:5]; // reason u have 5 buttons

<强>步骤-2

 create button progrmatically else if your button has already added in connection attribute ,just add the button to array

    //Initially set all Image are off mode 
    [RadioBtn1 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
    //create the common method for all Buttons
    [RadioBtn1 addTarget:self action:@selector(RadioButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.buttonsArray addObject:RadioBtn1];


    [RadioBtn2 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
    [RadioBtn2 addTarget:self action:@selector(RadioButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.buttonsArray addObject:RadioBtn2];


    [RadioBtn3 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
    [RadioBtn3 addTarget:self action:@selector(RadioButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.buttonsArray addObject:RadioBtn3];


    [RadioBtn4 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
    [RadioBtn4 addTarget:self action:@selector(RadioButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.buttonsArray addObject:RadioBtn4];


    [RadioBtn5 setImage:[UIImage imageNamed:@"radio-off.png"] forState:UIControlStateNormal];
    [RadioBtn5 addTarget:self action:@selector(RadioButton:) forControlEvents:UIControlEventTouchUpInside];

    [self.buttonsArray addObject:RadioBtn5];

<强>步骤-3

- (IBAction)RadioButton:(UIButton*)sender{

   //selection reset all buttons to normal state
   [self resetAllButtonsonNormalMode];

   [sender setImage:[UIImage imageNamed:@"radio-on.png"] forState:UIControlStateNormal];

}

<强>步骤4

-(void) resetAllButtonsonNormalMode{
       for(int i=0;i<[self.buttonsArray count];i++){
          UIButton* button=[self.buttonsArray objectAtIndex:i];
          [button setImage:[UIImage imageNamed:@"radio-off.png"]  forState:UIControlStateNormal];
       }
  }