Reputation: 2037
I'm trying to create a uibutton to work as a checkbox. Everything is working fine but the view: I'm setting to change the view when clicked. When it is supposed to show no checkmark it's fine, but when I need to show the checkmark, it's not working. This is what happens:
And this is the code:
- (void)viewDidLoad {
[super viewDidLoad];
[self.myButton setTitle:@"\u2610" forState:UIControlStateNormal];
[self.myButton setTitle:@"\u2610" forState:UIControlStateHighlighted];
[self.myButton setTitle:@"\u2610" forState:UIControlStateDisabled];
[self.myButton setTitle:@"\u2610" forState:UIControlStateNormal];
[self.myButton setTitle:@"\u2611" forState:UIControlStateSelected];
}
//action sent to the button when touched up inside
- (IBAction)moneyButtonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
What is wrong?
Regards!
Upvotes: 1
Views: 1029
Reputation: 23892
I think you forgot to add action event from your storyboard or by code
- (void)viewDidLoad {
[super viewDidLoad];
[self addMenuButton];
[self.myButton setTitle:@"\u2610" forState:UIControlStateNormal];
[self.myButton setTitle:@"\u2611" forState:UIControlStateSelected];
[self.myButton addTarget:self action:@selector(moneyButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)moneyButtonClicked:(UIButton *)sender {
NSLog(@"%d",sender.selected);
sender.selected = !sender.selected;
}
Button type must be Custom else you will found the tint color of button with the selection.
Outputs :
Deselected :
Selected :
Upvotes: 2
Reputation: 2037
Answers from ooops and Ashish Kakkad, but the problem with my code was: in the interface builder, my button was set as a System button and not as a Custom.
Upvotes: 1
Reputation: 803
I just create a new project and add the following code. It works like the gif shows. You can do a compare.
- (void)viewDidLoad {
[super viewDidLoad];
self.checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.checkButton addTarget:self action:@selector(moneyButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
self.checkButton.frame = CGRectMake(50, 50, 50, 50);
self.checkButton.titleLabel.textColor = [UIColor redColor];
self.checkButton.backgroundColor = [UIColor yellowColor];
[self.checkButton setTitle:@"\u2610" forState:UIControlStateNormal];
[self.checkButton setTitle:@"\u2611" forState:UIControlStateSelected];
[self.view addSubview:self.checkButton];
}
- (IBAction)moneyButtonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
button.selected = !button.selected;
}
Upvotes: 2