【问题标题】:IBOutletCollection of UIButtons - changing selected state of buttonsUIButtons 的 IBOutletCollection - 更改按钮的选定状态
【发布时间】:2012-06-04 21:10:28
【问题描述】:

我在一个视图中遇到了多个 UIButtons 的问题。我希望单独选择按钮,一次选择多个(例如:10 个按钮,选择按钮 1、4、5、9)。

在我的标题中,我有一个 IBOutletCollection 的属性:

@property (retain, nonatomic) IBOutletCollection(UIButton) NSMutableArray *buttonToStaySelected;

在我的实现中,我有一个 IBAction:

-(IBAction)selectedButton:(id)sender{
  for (UIButton *b in self.buttonToStaySelected) {
     if (b.isSelected == 0){
        [b setSelected:YES];
  } else
        [b setSelected:NO];
  }
}

我遇到的问题是,当我选择与集合相关的任何按钮时,它们都会变为选中状态。我知道问题很可能(几乎可以肯定)出在循环中,但是我尝试规定的每个条件都会破坏代码,并且没有一个按钮能够“更改”状态。

更新

为了让它们可选择、更改状态并检查多个,我将其用作我的最终代码:

-(IBAction)selectedButton:(id)sender {
  for (UIButton *b in self.buttonToStaySelected) {
      if (sender == b) {
      [b setSelected:!b.isSelected];
    }
   }
  }

感谢大家的帮助!

【问题讨论】:

    标签: objective-c ios xcode ios5


    【解决方案1】:

    selectButton: 消息发送时带有一个参数,该参数指定被点击的按钮,但您将操作应用于集合中的所有按钮,而不仅仅是被点击的按钮。

    -(IBAction)selectedButton:(id)sender
    {
      for (UIButton *b in self.buttonToStaySelected)
      {
         if (sender == b)
         {
            b.isSelected == !b.isSelected
         }
      }
    }
    

    【讨论】:

    • 那行得通。只要未选择另一个按钮,它只允许 setSelected 方法持续存在。我会摆弄它,但这肯定更正轨。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2016-08-01
    • 2019-12-11
    • 2011-10-30
    相关资源
    最近更新 更多