1

我有一个button改变它被按下的图像,它从img1img2。我现在还希望在按下某个按钮时更改文本。所以它从“你好”开始,然后按下它变成“再见”。

这是我目前的代码:

- (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];
 }
4

3 回答 3

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];
}
于 2013-09-18T10:04:04.887 回答
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;
}
于 2013-09-17T18:29:56.313 回答
1

将此添加到您的toggleImage方法中:

[bt1 setTitle:@"goodbye" forState: UIControlStateNormal];
于 2013-09-17T16:23:12.383 回答