带有 UIButton 单选按钮的 UICollectionViewCell - 一次选择一个单选按钮
Posted
技术标签:
【中文标题】带有 UIButton 单选按钮的 UICollectionViewCell - 一次选择一个单选按钮【英文标题】:UICollectionViewCell with UIButton radio button - one radioButton selected at time 【发布时间】:2019-06-10 02:41:53 【问题描述】:我有 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];
【问题讨论】:
每个单元格中有多个按钮还是每个单元格只包含一个按钮? @RajeshKumarR 每个单元格包含一个按钮 显示项目方法的项目数和单元格 @RajeshKumarR 我正在为单元格加载 UICollectionViewCell.xib,所以没有数据源方法 【参考方案1】: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];
希望这会有所帮助
【讨论】:
以上是关于带有 UIButton 单选按钮的 UICollectionViewCell - 一次选择一个单选按钮的主要内容,如果未能解决你的问题,请参考以下文章