按下按钮时更改标签
Posted
技术标签:
【中文标题】按下按钮时更改标签【英文标题】:Change label when a button has been pressed 【发布时间】:2013-09-17 16:17:54 【问题描述】:我有一个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];
【问题讨论】:
【参考方案1】:试试这个
- (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];
【讨论】:
【参考方案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;
【讨论】:
【参考方案3】:将此添加到您的toggleImage
方法:
[bt1 setTitle:@"goodbye" forState: UIControlStateNormal];
【讨论】:
以上是关于按下按钮时更改标签的主要内容,如果未能解决你的问题,请参考以下文章