我有两个状态的简单UIButton
。我为button
UIControlEventTouchDown
事件添加了一项操作。当button
处于正常状态时,一切都很好,当我触摸button
时会调用方法。但当button
位于selected state
时,当我触摸button
时没有任何反应,只有当我释放手指时,状态才会变为正常状态(如UIControlEventTouchUpInside
)。
我该如何解决这个问题?
我使用这种方法创建我的按钮:
- (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];
}
答案 0 :(得分: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];
}