帮助iOS上的setTitle

Jay*_*lor 0 cocoa-touch objective-c

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

buttonTestViewController.h

#import <UIKit/UIKit.h>

@interface buttonTestViewController : UIViewController {
}

-(IBAction)pressButton:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*c W 6

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

static int counter = 0;
Run Code Online (Sandbox Code Playgroud)

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

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

编辑

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

[[sender titleLabel] setText:@"not answered"];
Run Code Online (Sandbox Code Playgroud)

  • 除非我弄错了,否则在方法体中使用静态声明应该没问题.它应该只被初始化一次. (2认同)