ranjha
ranjha

Reputation: 91

Create a toggle out of a UIButton not working?

everyone!

So basically, I am trying to create a simple toggle out of my UIButton. With the code below, I am able to click the button, but only for a brief moment do I see @"Expense" as the title. It is probably a VERY simple mistake. Any help is appreciated!

- (IBAction)typeChanger {
if ([typeButton.titleLabel.text isEqual:@"Income"]) {
    typeButton.titleLabel.text = @"Expense";
}else if ([typeButton.titleLabel.text isEqual:@"Expense"]) {
    typeButton.titleLabel.text = @"Income";
}
}

Thanks in advance!

Upvotes: 0

Views: 151

Answers (3)

Pratik Mistry
Pratik Mistry

Reputation: 2945

This may be very useful and handy. Try this out.

https://github.com/Brayden/UICheckbox

Upvotes: 2

JRG-Developer
JRG-Developer

Reputation: 12663

You use NSString's isEqualToString: method instead of isEqual for string comparisons (either should work, but it's faster according to the docs).

Also, you need to use setTitle:forState: to set the title of a UIButton... the two important states to set are UIControlStateNormal (not pressed) and UIControlStateHighlighted (for when it's pressed):

- (IBAction)typeChanger {
    if ([[typeButton titleForState:UIControlStateNormal] isEqualToString:@"Income"]) {
         [typeButton setTitle:@"Expense" forState:UIControlStateNormal];
         [typeButton setTitle:@"Expense" forState:UIControlStateHighlighted];

    } else if ([[typeButton titleForState:UIControlStateNormal] isEqualToString:@"Expense"]) {
         [typeButton setTitle:@"Income" forState:UIControlStateNormal];
         [typeButton setTitle:@"Income" forState:UIControlStateHighlighted];
    }
}

See also the docs on NSString:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

And on UIButton:

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIButton_Class/UIButton/UIButton.html

Upvotes: 0

Venk
Venk

Reputation: 5955

Do like this,

- (IBAction)typeChanger {
if ([typeButton.titleLabel.text isEqual:@"Income"]) {
   [typeButton setTitle:@"Expense" forState:UIControlStateNormal];
}else if ([typeButton.titleLabel.text isEqual:@"Expense"]) {
    [typeButton setTitle:@"Income" forState:UIControlStateNormal];
}
}

Upvotes: 2

Related Questions