1

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

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

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

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

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

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

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

提前致谢

4

1 回答 1

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;
}
于 2013-01-21T15:35:56.590 回答