按下button后,标题消失

我正在尝试创build一个像这样的push-on-push-off-likebutton,虽然我的代码有点不同:

UIButton* alertsButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; alertsButton.frame = CGRectMake(170, 43.5, 130, 130); [alertsButton.titleLabel setFont:[UIFont fontWithName:@"Novecento wide" size:22]]; [alertsButton setTitle:NSLocalizedString(@"Alerts", nil) forState:UIControlStateHighlighted]; [alertsButton setTitle:NSLocalizedString(@"Alerts", nil) forState:UIControlStateNormal]; [alertsButton setTitle:NSLocalizedString(@"Alerts", nil) forState:UIControlStateSelected]; [alertsButton addTarget:self action:@selector(toggleAlerts:)forControlEvents:UIControlEventTouchUpInside]; -(void)toggleAlerts:(id)sender { UIButton *button = (UIButton *)sender; if (button.selected) { button.selected = NO; [button setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateNormal]; [button.titleLabel setFont:[UIFont fontWithName:@"Novecento wide" size:22]]; NSLog(button.titleLabel.text); } else { button.selected = YES; [button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateNormal]; [button.titleLabel setFont:[UIFont fontWithName:@"Novecento wide" size:22]]; NSLog(button.titleLabel.text); } } 

当我按下button时,背景会按预期改变,但标签消失,尽pipe文本显示在debugging控制台中。 我试过这个没有结果:(

那是因为你的形象超越了你的标签。

而不是[button setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateNormal];

[button setBackgroundImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateNormal];

你的上下影像是多大?

如果他们太大,他们会把文本推出。 正如Nikita所说,如果图像应该是背景,请使用setBackgroundImage方法