带有UIButton单选按钮的UICollectionViewCell-一次选择了一个radioButton

时间:2019-06-10 02:41:53

标签: objective-c uicollectionview radio-button uicollectionviewcell

在UICollectionViewCell.xib中,我有带有UIButton的UICollectionView作为单选按钮。

我需要一次选择一个单选按钮,如果按下了下一个,则应取消选择上一个。我将不胜感激。

//Loading radio button when view loads
-(void)setRadioButton{

    if (!self.product.isSelectedCell) {
        [self.radioBtn setBackgroundImage:[UIImage imageNamed:@"radio-button"] forState:UIControlStateNormal];
    }
    else
    {
        [self.radioBtn setBackgroundImage:[UIImage imageNamed:@"radio-button-select"] forState:UIControlStateNormal];
    }
}

//Action for radio button
- (IBAction)radioBtnAction:(UIButton*)sender {

    if([self.radioBtn isSelected]==YES)
    {
      [self.radioBtn setBackgroundImage:[UIImage imageNamed:@"radio-button-select"] forState:UIControlStateNormal];

    }
       else{
//always calls else 
            [self.radioBtn setBackgroundImage:[UIImage imageNamed:@"radio-button"] forState:UIControlStateNormal];

        }
    }

1 个答案:

答案 0 :(得分:0)

Use this code in cellForRowAtIndexPath

        UIButton *radioButton = (UIButton *) [cell.contentView viewWithTag:kRadioButtonTag]; // Radio button
        [radioButton setImage:[UIImage imageNamed:@"radio_unselected"] forState:UIControlStateNormal];
        [radioButton setImage:[UIImage imageNamed:@"RadioSelected"] forState:UIControlStateSelected];
        [radioButton addTarget:self action:@selector(radioButtonPressed:) forControlEvents:UIControlEventTouchDown]; 

if(indexPath == selectedIndexPath)
        [radioButton setImage:[UIImage imageNamed:@"RadioSelected"] forState:UIControlStateSelected];
else
        [radioButton setImage:[UIImage imageNamed:@"radio_unselected"] forState:UIControlStateNormal];

 Radio button taped from table cell and get index path of that button
Take on class Lebel NSIndexPath variable and store selected index path.

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

    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil) {
       selectedIndexPath = indexPath
[tableView reloadData];
    }
}

希望这会有所帮助