1
votes

Here's my code (it's wrapped in an IBAction that is called when the button is pressed):

if (myButton.currentTitle == @"test") {

    [myButton setTitle:@"test2" forState:UIControlStateNormal];
}

if (myButton.currentTitle == @"test2") {

    [myButton setTitle:@"test" forState:UIControlStateNormal];
}

I want the UIButton text to toggle when pressed (if text = "test" then change to "test2" and when pressed if text = "test2" change to "test").

I do have an IBOutlet connected for myButton and the the IBAction connected to myButton--so I am pretty sure it isn't a problem with my connections.

For some reason this isn't working, I'm sure I am missing something very simple.

5

5 Answers

2
votes

use isEqualToString: instead of ==

2
votes

This is because you lack a control statement that skips the second if when the first one succeeds. When you come into the block with "test", you switch it to "test2", and then the second condition succeeds immediately, and you turn "test2" back into "@test".

You can an an else to fix this, but you can skip the if altogether by using an NSArray that maps the current state to the new state.

// This should be made static, and initialized only once
NSDictionary *nextTitle = [NSDictionary dictionaryWithObjectsAndKeys:
    @"test", @"test2", @"test2", @"test", nil];

// This line does the toggling
[myButton setTitle:[nextTitle valueForKey:myButton.currentTitle] forState:UIControlStateNormal];
0
votes
if ([myButton.currentTitle isEqualToString:@"test"]) {

  [myButton setTitle:@"test2" forState:UIControlStateNormal];
 }

if ([myButton.currentTitle isEqualToString:@"test2"]) {

   [myButton setTitle:@"test" forState:UIControlStateNormal];
}

Hope, this will help you...

0
votes

Comparing user-visible strings is generally considered bad practice (and becomes tedious when you need to do i18n), especially with string literals since it's vulnerable to typos.

If you're just going to toggle between two states, the easiest thing to do is to use the UIControl.selected property (corresponding to UIControlStateSelected):

// In init
[myButton setTitle:@"test" forState:UIControlStateNormal];
[myButton setTitle:@"test2" forState:UIControlStateSelected];
[myButton setTitle:@"test2" forState:UIControlStateSelected|UIControlStateHighlighted];

// Toggle
myButton.selected = !myButton.selected;

It also makes the code a lot cleaner when you when you decide to toggle the button image/background/text colours too.

Note the slight gotcha: If you don't set the title for UIControlStateSelected|UIControlStateHighlighted it will use the title for UIControlStateNormal when the button is both selected and highlighted (touched).

-1
votes

When comparing strings to each other try using if([str1 compare:str2] == NSOrderedSame)