按住 UIButton(状态选择/突出显示),直到按下另一个按钮



我的视图控制器底部有 3 个按钮,btn1 btn2 btn3,我正在使用它们而不是选项卡栏,因为无法根据我的要求完全自定义选项卡栏。

现在的问题是,当按下 btn1 时,我希望它将其图像更改为灰色矩形,而不是正常状态图像。我已经在我为按钮声明的插座 btn1Outlet 中设置了两种状态的图像,使用插座的 setimage 和 uicontrolstate 属性。

问题是,在按下 btn2 或 btn3 之前,我无法保持按钮处于选中状态。 btn one 只有在按下所选状态图像时才会更改为所选状态图像,当我离开它的那一刻,它会变回正常状态。

如何在按下其他 2 个按钮中的任何一个之前将 btn1 的图像保留为所选图像?

您所做的是为"突出显示"状态设置一个图像,这就是为什么当您推送它时可以看到您的图像。

你想做的是

1) 将图像设置为"已选择"状态

2) 使用助手视图为视图控制器创建一个属性(只需控制将按钮拖动到标题)(在情节提要上,右上角的第二个方块)

3) 关于按钮操作类型的方法:

button.selected = !button.selected;

(显然将按钮替换为您命名属性的任何内容)

这是我所做的:

  1. 将所有 3 个按钮链接到以下操作方法
  2. 创建所有 3 个按钮的数组
  3. 将调用该方法的按钮设置为已选中
  4. 将其他 2 个按钮设置为未选中

    - (IBAction)buttonPressed:(id)sender
    {
        NSArray* buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, nil];
        for (UIButton* button in buttons) {
            if (button == sender) {
                button.selected = YES;
            }
            else {
                button.selected = NO;
            }
        }
    }
    

希望这有帮助。

干杯!

要保持按钮处于选中状态,您需要在按钮调用的方法中调用 setSelected:YES。例如:

- (void) methodThatYourButtonCalls: (id) sender {
        [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0];

}
- (void) flipButton:(UIButton*) button {
    if(button.selected) 
        [button setSelected:NO];
    else
        [button setSelected:YES];
}

我知道调用 performSelector 看起来有点奇怪:而不仅仅是调用 [sender setSelected:YES],但后者对我不起作用,而前者却对我有用!

为了让按钮在

按下不同的按钮时取消选择,我建议添加一个实例变量,其中包含指向当前所选按钮的指针,因此当触摸新按钮时,您可以调用 flipButton: 以相应地取消选择旧按钮。所以现在你的代码应该读:

添加指向接口的指针

@interface YourViewController : UIViewController
{
    UIButton *currentlySelectedButton;
}

和这些方法来实现

- (void) methodThatYourButtonCalls: (id) sender {
    UIButton *touchedButton = (UIButton*) sender;
    //select the touched button 
    [self performSelector:@selector(flipButton:) withObject:sender afterDelay:0.0]; 
    if(currentlySelectedButton != nil) { //check to see if a button is selected...
        [self flipButton:currentlySelectedButton];
    currentlySelectedButton = touchedButton;
}
- (void) flipButton:(UIButton*) button {
    if(button.selected) 
        [button setSelected:NO];
    else
        [button setSelected:YES];
}

最新更新