iPhone iOS 4 UIButton切换高亮状态的开关



我在我的iPhone 4应用程序的界面构建器中设置了一个样式为"Info Dark"的UIButton。该按钮的其中一个属性是" highlight ",它在按钮周围显示一个白色高亮。

我想切换这个白色高亮打开和关闭,表明按钮功能是否有效。

在界面构建器中使用以下回调函数链接"Touch up inside"事件:

infoButton.highlighted = !infoButton.highlighted;

在第一次触摸之后,高亮消失,并且不像我期望的那样切换。我还需要做什么才能使高亮切换并显示按钮的状态?

谢谢!

更新:当从界面构建器加载时,即使视图出现/消失,按钮也会保持高亮显示。导致这种情况发生的是"显示触摸高亮"界面构建器属性。如果我将上面的代码分配给另一个按钮,那么信息按钮就会像预期的那样亮起和关闭。但是,info按钮本身的触摸会干扰上述代码,导致按钮失去"触摸"高亮

更新2:我在界面构建器中添加了另一个信息按钮,直接在第一个信息按钮下方,并使其永久发光。为了创建切换的外观,我在实际按钮下方隐藏和取消隐藏glowInfoButton。如下图所示:

    infoButton.highlighted = NO;
    glowInfoButton.highlighted = YES;
    glowInfoButton.enabled = NO;
    glowInfoButton.hidden = YES;
- (IBAction)toggleInfoMode:(id)sender {
//    infoButton.selected = !infoButton.selected;
    glowInfoButton.hidden = !glowInfoButton.hidden;
 }

Highlighted图像是当UIButton被按下时显示的,并且在UIButton本身中被控制。

您正在寻找Selected属性。你可以设置一个选定的图像在IB,然后把infoButton.selected = !infoButton.isSelected;在你的TouchUpInside回调。

突出显示的属性不是这样工作的,按钮不是切换。

这只是为了知道按钮是否被按下,如果我是正确的。

如果你想实现这个功能,我建议你子类化UIButton或UIControl。

现在我看到你真正是什么之后,我会建议子类UIButton和检查调用一个事件,然后相应地切换高亮状态。您可以在不添加虚拟按钮的情况下完成此操作。

在自定义按钮类实现文件中放置以下代码或类似代码:

#import "HighlightedButton.h"
@implementation HighlightedButton
BOOL currentHighlightState;
-(void)toggleHighlight:(id)sender {
  self.highlighted = currentHighlightState;
}
-(void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
  //get the string indicating the action called
  NSString *actionString = NSStringFromSelector(action);
  //get the string for the action that you want to check for
  NSString *touchUpInsideMethodName = [[self actionsForTarget:target forControlEvent:UIControlEventTouchUpInside] lastObject];
  if ([touchUpInsideMethodName isEqualToString:actionString]){
    //toggle variable
    currentHighlightState = !currentHighlightState;
    //allow the call to pass through
    [super sendAction:action to:target forEvent:event];
    //toggle the property after a delay (to make sure the event has processed)
    [self performSelector:@selector(toggleHighlight:) withObject:nil afterDelay:.2];
  } else {
    //not an event we are interested in, allow it pass through with no additional action
    [super sendAction:action to:target forEvent:event];
  }
}
@end

这是一个快速运行在一个适当的解决方案,有一个闪烁的切换,你可能不喜欢。我敢肯定,如果你玩一些变化可以纠正。我试过了,实际上很喜欢你所说的情况。

UIButton的高亮状态就是简单地将按钮的alpha值设置为0.5f。因此,如果你设置按钮不改变高亮,那么只需在0.1和0.5之间切换alpha值。

例如:

- (void)buttonPressed:(id)sender {
    if((((UIButton*)sender).alpha) != 1.0f){
        [((UIButton*)sender) setAlpha:1.0f];
    } else {
        [((UIButton*)sender) setAlpha:0.5f];
    }
}

也许你真正想要的是

infoButton.enabled = NO;

当设置为no时,将使按钮变暗并禁用触摸,当设置为YES时允许正常操作。

或者

infoButton.enabled = !infoButton.isEnabled;

切换相同的可用性。

如果你把它放在touchupinside事件中,当然它只会在第一次起作用。之后被禁用并且不接收触摸事件。你可以把它放在另一个方法中,这个方法决定是否应该启用按钮。

如果你真的希望每次按下它都改变,那么你可能应该使用一个开关,或者你可以看看-imageForState, -setTitle:forState和/或-setTitleColor:forState方法。如果您想在每次触摸时切换外观,您可以更改这些

最新更新