UIButton - 没有显示复选标记

时间:2015-08-10 17:37:16

标签: ios objective-c uibutton

我正在尝试创建一个uibutton作为复选框。一切都工作正常,但视图:我设置在点击时更改视图。如果它没有显示任何复选标记,那很好,但是当我需要显示复选标记时,它不起作用。这就是:

image with no checkmark image with checkmark

这是代码:

- (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;
}

有什么问题?

问候!

3 个答案:

答案 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;
}

按钮类型必须是自定义,否则您将找到带有选择的按钮的色调颜色。

enter image description here

输出:

取消选择:

enter image description here

选择:

enter image description here

答案 1 :(得分:2)

我只是创建一个新项目并添加以下代码。它像gif节目一样工作。你可以做比较。

enter image description here

- (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)

来自ooops和Ashish Kakkad的答案,但我的代码的问题是:在界面构建器中,我的按钮被设置为系统按钮而不是自定义。

enter image description here