I am a rookie with programming. I have entered in the following code and the app runs without bugs but crashes when the button is pressed. The goal is to identify if the button is pressed once or twice. If it is pressed a third time, it should reset to never being pressed.
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
I would also like to change the background color of the button when pressed and I continue to get errors if I use setBackgroundColor. Thank you in advance for your time and consideration.
You need to initialize
counter. It could be any number in the legal range ofints with how you have it right now, and it changes every time this method is called.Also move that line outside of your method declaration so
counterisn’t reset to 0 every time the method is called. Or use an instance variable instead of a static one. That’s all you should need to get this working.What error do you get when you try to use
setBackgroundColor:?Edit
Also, if your control is a
UIButton,setTitle:isn’t a valid method. Check the API docs from Apple. You’d need to do something like: