【问题标题】:When clicking first button,it becomes highlighted and while clicking second,second highlighted and first become normal单击第一个按钮时,它变为突出显示,单击第二个,第二个突出显示,第一个变为正常
【发布时间】:2015-03-19 10:37:01
【问题描述】:

我正在创建一个应用程序,其中包含五个按钮,以编程方式创建。以下是要求...

单击第一个按钮时,它保持突出显示。单击第二个按钮时,第一个变为正常,第二个保持突出显示...即单击的特定按钮变为突出显示,所有其他按钮保持正常........请帮助..

【问题讨论】:

  • 请出示您的代码。 Stackoverflow 是一个帮助您解决代码问题的网站,而不是为您编写代码
  • 您的问题有 3 个答案,因此您应该通过单击复选标记“接受”其中一个答案! (见meta.stackexchange.com/questions/5234/…)。 - 对于后续问题,请发布一个新问题。

标签: objective-c ios7 xcode5


【解决方案1】:

你可以设置

[button setBackgroundImage:[UIImage imageNamed:@"normalbackgroundimage"] forState:UIControlStateNormal]; //not highlighted
[button setBackgroundImage:[UIImage imageNamed:@"highlightedbackgroundimage"] forState:UIControlStateHighlighted | UIControlStateSelected]; //highlighted

现在,当您设置 button.selected = YES 时,它将突出显示

所以你可以在按钮点击时做这样的事情

button1.selected = YES;
otherButton.selected = NO;

编辑

解决您的问题的简单方法是创建一个 ibaction 将其连接到您想要选择/取消选择的所有按钮,然后执行此操作

-(IBAction)someButtonPressed:(UIButton*)sender{
    button1.selected = NO;
    button2.selected = NO;
    button3.selected = NO; //and so on...just set all your buttons to selected = NO

    //at the end you just select button you clicked
    sender.selected = YES;
}

【讨论】:

    【解决方案2】:

    这将是我的解决方案:

    获取一个属性来跟踪所选按钮

    @property (nonatomic, weak) UIBUtton *lastSelectedButton;
    

    在您的按钮回调方法(添加按钮时配置的选择器)中:

    - (void)didClickButton:(UIButton *)button {
        if (self.lastSelectedButton isEqual:button) {
            // Don't need to do anything in this case because the button is already selected
            return;
        }
        [self.lastSelectedButton setSelected:NO];
        [button setSelected:YES];
        [self setLastSelectedButton:button];
    }
    

    如果您有任何问题或需要更多帮助,请告诉我!

    【讨论】:

      【解决方案3】:

      您可以创建一个实例变量int,其中包含一个标签值。现在,无论您单击哪个按钮,都需要清除前一个按钮的标记值并将其分配给当前按钮。

      例如:

      int const TAG_HIGHLIGHTED_BUTTON = 100;
      
      - (void)buttonAction:(UIButton *)button {
          UIButton *prevButton = [self.view viewWithTag:TAG_HIGHLIGHTED_BUTTON];
          [prevButton setTag:0];
      
          [button setTag:TAG_HIGHLIGHTED_BUTTON];
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-06
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-17
        • 1970-01-01
        • 2014-03-16
        • 1970-01-01
        相关资源
        最近更新 更多