我正在尝试创建一个uibutton作为复选框。一切都工作正常,但视图:我设置在点击时更改视图。如果它没有显示任何复选标记,那很好,但是当我需要显示复选标记时,它不起作用。这就是:
这是代码:
- (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;
}
有什么问题?
问候!
答案 0 :(得分:2)
我想您忘记在故事板或代码中添加动作事件
- (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;
}
按钮类型必须是自定义,否则您将找到带有选择的按钮的色调颜色。
输出:
取消选择:
选择:
答案 1 :(得分:2)
我只是创建一个新项目并添加以下代码。它像gif节目一样工作。你可以做比较。
- (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;
}
答案 2 :(得分:1)