我已经以编程方式创建了一个带有normalState图像的按钮。 但是我想在按下按钮时设置一个新的按钮图像(新图像应该在其余时间显示)。我尝试了一些东西,但它只在点击期间有效。因此,按钮会在再次点击后显示其旧图像。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"image1.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(15.0f, 32.0f, 24.0f, 20.0f);
[cell addSubview:button];
感谢您的帮助。
答案 0 :(得分:0)
尝试使用它可以帮助你。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"image1.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"image2png"] forState:UIControlStateHighlighted];
button.frame = CGRectMake(15.0f, 32.0f, 24.0f, 20.0f);
// ----------- Add this line in your code -------
[button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
- (void)btnPressed:(UIButton *)sender
{
[sender setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal];
}
答案 1 :(得分:0)
您必须在按钮的目标中进行设置。添加以下代码:
[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
并在该方法中为UIControlStateNormal
:
- (void)buttonTapped:(UIButton *)sender {
[button setBackgroundImage:[UIImage imageNamed:@"image2png"] forState:UIControlStateNormal];
}