如何禁用UIButton高亮操作

时间:2013-01-21 14:38:27

标签: iphone ios objective-c uibutton

我正在尝试用两个按钮实现分段控制的模拟。在默认状态下,它们没有图像,只有标签,在选定的图像中,它们具有背景图像。我想用TouchDown事件激活控制。

这是代码(我删除了所有不必要的东西):

-(IBAction) onButton1
{
    button1.selected = YES;
    button2.selected = NO;
}

-(IBAction) onButton2
{
    button1.selected = NO;
    button2.selected = YES;
}

问题是:假设选择了button1。当我触摸button2时,它不会将其图像更改为“选定”图像(没有默认图像,正如我所说),但是当我释放手指时它会发生变化。此外,如果我触摸已选择的按钮,它将删除“已选择”的图像,并在我释放它时将其返回。

我设置了按钮的突出显示状态,因此他们在该状态下“选择”了图像,但它没有帮助(不仅在IB中,而且在[button setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateHighlighted];)。我已经设置了adjustsImageWhenHighlighted = NO,这在程序方式和IB方面都没有帮助。

我在这里看到了很多相似(但不完全相同)的问题,但它们对我不起作用。

提前致谢

1 个答案:

答案 0 :(得分:0)

因为,你想在触地事件中激活动作,我认为你不需要突出显示。请尝试以下代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(10.0f, 10.0f, 50.0f, 50.0f);
    [button1 setBackgroundImage:[UIImage imageNamed:@"btn.jpeg"] forState:UIControlStateNormal];
    [button1 setBackgroundImage:[UIImage imageNamed:@"btnsel.jpeg"] forState:UIControlStateSelected];
    [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchDown];
    [button1 addTarget:self action:@selector(button1TouchUp:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];

    [self.view addSubview:button1];
    button1.selected = YES;

    button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(80.0f, 10.0f, 50.0f, 50.0f);
    [button2 setBackgroundImage:[UIImage imageNamed:@"btn.jpeg"] forState:UIControlStateNormal];

    [button2 setBackgroundImage:[UIImage imageNamed:@"btnsel.jpeg"] forState:UIControlStateSelected];
    [button2 addTarget:self action:@selector(button2Action:) forControlEvents:UIControlEventTouchDown];
    [button2 addTarget:self action:@selector(button2TouchUp:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];

    [self.view addSubview:button2];
}

- (void)button1Action:(UIButton*)sender
{
    button1.highlighted = NO;
    button1.selected = YES;
    button2.selected = NO;
}

- (void)button2Action:(UIButton*)sender
{
    button2.highlighted = NO;
    button2.selected = YES;
    button1.selected = NO;    
}

- (void)button1TouchUp:(id)sender
{
    button1.highlighted = NO;
}

- (void)button2TouchUp:(id)sender
{
    button2.highlighted = NO;
}