1

我有UIButton两种状态。button我在forUIControlEventTouchDown事件中添加了一个动作。当button处于正常状态时一切正常,当我触摸button. 但是当我触摸时没有任何button反应,只有当我松开手指时,状态才会变为正常(Like )。selected statebuttonUIControlEventTouchUpInside

我该如何解决这个问题?

我使用这种方法创建我的按钮:

- (UIButton *) createButtonWithFrame:(CGRect)frame title:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0x3a3a3a) forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [[button titleLabel] setFont:[UIFont fontWithName:@"Gotham-Bold" size:10]];
    [button setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"button_pressed.png"] forState:(UIControlStateSelected)];
    [button setAdjustsImageWhenHighlighted:NO];
    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
    return button;
}

是这样buttonPressed:的:

- (void) buttonPressed:(UIButton *)sender {
    [sender setSelected:!sender.selected];
}
4

1 回答 1

0

尝试这个,

从您的代码中删除此行

[button setBackgroundImage:[UIImage imageNamed:@"button_pressed.png"] forState:(UIControlStateSelected)];

并这样做,

- (void) buttonPressed:(UIButton *)sender {

    if([[sender backgroundImageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:@"button.png"]])
        [sender setBackgroundImage:[UIImage imageNamed:@"button_pressed.png"] forState:UIControlStateNormal];
    else
        [sender setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
}
于 2013-06-14T09:54:20.187 回答