我有button
更改已按下的图片,它从img1
变为img2
。我现在也希望在按下某个按钮时更改文本。所以它从“你好”开始,然后当按下时它转向“再见”,例如。
这是我目前的代码:
- (void)toggleImage:(UIButton *)btn1 {
self.btn1ImageName = ([self.btn1ImageName isEqualToString:@"greypad.png"]) ? @"greenpad.png" : @"greypad.png";
[btn1 setImage:[UIImage imageNamed:self.btn1ImageName] forState:UIControlStateNormal];
}
viewDidLoad中:
[self addLabel];
self.btn1ImageName = @"greypad.png";
btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setFrame:CGRectMake(46, 67, 48, 48)];
[btn1 setImage:[UIImage imageNamed:self.btn1ImageName] forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(toggleImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
标签?
-(void)addLabel{
UILabel *aLabel = [[UILabel alloc]initWithFrame: CGRectMake(20, 200, 280, 80)];
aLabel.numberOfLines = 0;
aLabel.textColor = [UIColor blueColor];
aLabel.backgroundColor = [UIColor clearColor];
aLabel.text = @"hello";
[self.view addSubview:aLabel];
}
答案 0 :(得分:3)
试试这个
- (void)toggleImage:(UIButton *)btn1 {
self.btn1ImageName = ([self.btn1ImageName isEqualToString:@"greypad.png"]) ? @"greenpad.png" : @"greypad.png";
self.titleStr = ([self.titleStr isEqualToString:@"hello"]) ? @"goodbye" : @"hello";
[btn1 setImage:[UIImage imageNamed:self.btn1ImageName] forState:UIControlStateNormal];
[btn1 setTitle:self.titleStr forState:UIControlStateNormal];
}
答案 1 :(得分:2)
我会推荐一种不同的方法:
设置按钮时,为不同状态设置不同的标题和图像
[btn1 setTitle:@"hello" forState: UIControlStateNormal];
[btn1 setTitle:@"goodbye" forState: UIControlStateSelected];
[btn1 setImage:[UIImage imageNamed:@"greypad.png"] forState:UIControlStateNormal];
[btn1 setImage:[UIImage imageNamed:@"greenpad.png"] forState:UIControlStateSelected];
在您的切换方法中,只需执行
- (void)toggleImage:(UIButton *)button
{
button.selected = !button.selected;
}
答案 2 :(得分:1)
将此添加到您的toggleImage
方法:
[bt1 setTitle:@"goodbye" forState: UIControlStateNormal];