多个按钮,但一次只能按下一个

Multiple Buttons, But only one pressed at a time

我一直在浏览该站点,但找不到任何可以回答我问题的内容。在我的应用程序中,我有一个模态对话框,显示一个使用自定义单元格且仅包含一个 UIButton 的 UICollectionView。

我已将按钮设置为 select 可用,而不是单击。我只想允许一次 selected 一个按钮,当一个按钮被 selected 时,我希望禁用该部分中的其他按钮。我不确定如何解决这个问题,因为我对 IOS 还是很陌生。下面的屏幕截图显示了模型和按钮的基本外观。

目前我可以 select 多个按钮,但我需要它是单个 selection 并且当一个按钮被 selected 时,其余按钮将被禁用。目前,我为我的自定义 UICollectionViewCell 在 class 中提交了 selected,并将其包含在下面。任何帮助和建议都会很棒,我只需要指出正确的方向。

- (IBAction)Selected:(id)sender {
    if(_Button.selected == 0)
    {
        [_Button setSelected:YES];        
    }
    else
    {
        [_Button setSelected:NO];
    }
}

在集合视图数据源方法中 - collectionView:cellForItemAtIndexPath:配置单元格时,将indexPath项的值设置为单元格中对应按钮的标签。

然后维护一个 属性 说,previousSelectedButtonIndex 您可以在其中维护先前 selected 索引的值。

在您的按钮单击处理程序中,如果 previousSelectedButtonIndex 包含一个值,如果是,则删除 select 该按钮,select 新按钮并将 previousSelectedButtonIndex 设置为新值。

请注意,您可能需要进行一些错误处理,但基本上这是可以实现的。

声明一个全局变量为

NSInteger selectedIndex;

也将 -1 值设置为 selectedIndex,因为最初没有选择任何按钮。

selectedIndex = -1;

然后在UICollectionView

的数据源方法中写入
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
 {
    //here create cell object of UICollectionViewCell
    cell.button.tag = indexPath.row;
    [cell.button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    if(indexPath.row == selectedIndex)
    {
      //show this button as selected by setting different name/color/image for button
       cell.button.enabled = TRUE;
    }
    else
       cell.button.enabled = FALSE;
    return cell;
}


- (void) buttonPressed:(id)sender
  {
    UIButton *selectedButton = (UIButton *)sender;
    if(selectedIndex == selectedButton.tag)
        selectedIndex = -1; //deselect the selected button
    else
        selectedIndex = selectedButton.tag; //select the tapped button
    [self.collectionView reloadData];
  }

您或许应该使用一组按钮。 Apple 赋予了同时控制一系列按钮的能力。尝试阅读本文以了解如何实现这一目标。 Outlet Collections