user2388466
user2388466

Reputation: 1

UIButton change title on press using a counter

I get an error with the code below.. I'm banging my head against the wall because I can't figure out why I can't seem to have the message updated with the number of button presses (a counter) each time you press the button...

- (IBAction)countButtonTapped:(id)sender {

    self.pressCount+=1;
    //int count = (int)self.pressCount;

    //[self.tapCountButton setTitle:@"I've been tapped %i time(s)!" forState:UIControlStateNormal];
    //[self.tapCountButton setTitle:@"I've hit the main button!" forState:UIControlStateNormal];
    //NSLog(@"I've been tapped %lu time(s)!", (unsigned long)self.pressCount);
    [(UIButton *)sender setTitle:@"I've been tapped %@ time(s)!",self.pressCount forState:UIControlStateNormal];

Upvotes: 0

Views: 178

Answers (2)

Sam B
Sam B

Reputation: 27598

Make sure that in your story board, your UIButton calls IBAction on touchdown only. Perhaps you are calling your IBAction on other UIButton states.

This is how I would do it

    @implementation v1ViewController

    ...
    static int counter = 0;


    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

    //initialize
    counter = 0
    }

    - (IBAction)countButtonTapped:(id)sender {

        counter++;

    NSLog("counter: %d ...", counter);

UIButton *button = (UIButton *) sender;
        [button setTitle:@"I've been tapped %d time(s)!",counter forState:UIControlStateNormal];

    }

Upvotes: 0

Michael Dautermann
Michael Dautermann

Reputation: 89509

Sounds like you simply need a string formatter.

Try this:

- (IBAction)countButtonTapped:(id)sender {
    UIButton * button = (UIButton *) sender; 
    self.pressCount+=1;
    NSString * titleForButton = [NSString stringWithFormat: @"I've been tapped %d time(s)!",self.pressCount]
    [button setTitle: titleForButton forState: UIControlStateNormal];
}

Another difference here is that "self.pressCount" is likely a NSInteger, so you want to use "%d" as the format argument and not "%@", which is meant to denote NSString objects.

Upvotes: 2

Related Questions