首页 > 解决方案 > 带有 UIButton 单选按钮的 UICollectionViewCell - 一次选择一个单选按钮

问题描述

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

我需要一次选择一个单选按钮,如果按下下一个,则应取消选择上一个。我会很感激帮助。

//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];

        }
    }

标签: objective-cuicollectionviewradio-buttonuicollectionviewcell

解决方案


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];
    }
}

希望这会有所帮助


推荐阅读