帮助iOS上的setTitle

时间:2011-01-26 03:20:43

标签: objective-c cocoa-touch

我是编程的新手。我输入了以下代码,应用程序运行时没有错误,但按下按钮时崩溃。目标是确定按钮是否被按下一次或两次。如果第三次按下它,它应该重置为永不被按下。

buttonTestViewController.h

#import <UIKit/UIKit.h>

@interface buttonTestViewController : UIViewController {
}

-(IBAction)pressButton:(id)sender;

@end

buttonTestViewController.m

@implementation buttonTestViewController


-(IBAction)pressButton:(id)sender{
static int counter;

if (counter == 0) {
    [sender setTitle:@"not answered"];
}else if (counter == 1) {
    [sender setTitle:@"Pressed Once"];
}else if (counter == 2) {
    [sender setTitle:@"Pressed Twice"];
}
counter += 1;

if (counter > 2) {
    counter = 0;
}
}
- (void)dealloc {
[super dealloc];
}

@end

我还想在按下时更改按钮的背景颜色,如果我使用setBackgroundColor,我会继续出错。提前感谢您的时间和考虑。

1 个答案:

答案 0 :(得分:6)

您需要初始化counter。它可以是int s的合法范围内的任何数字,以及您现在如何拥有它,并且每次调用此方法时它都会更改。

static int counter = 0;

同样在方法声明之外移动该行,这样每次调用方法时counter都不会重置为0。或者使用实例变量而不是静态变量。这就是你需要的所有工作。

尝试使用setBackgroundColor:时会出现什么错误?

修改

此外,如果您的控件是UIButton,则setTitle:不是有效方法。查看Apple的API docs。你需要做类似的事情:

[[sender titleLabel] setText:@"not answered"];