我想要做的是点击按钮时更改图像。此按钮效果很好,但我的按钮中的图像保持空白。在发布之前,我做了一些认真的研究。
我先看了Setting an image for a UIButton in code。虽然我不确定我的图像是否为零,但我跟着this instruction,这证实了我的图像不是零。我甚至did this,我再次确认Assets文件夹中存在的图像。
以下是我从控制台获得的内容:
2017-04-12 15:57:00.826779 + 0800 UIImage:0x170284a10,{64,64}
2017-04-12 15:57:00.976058 + 0800 UIImage:0x1702808c0,{64,64}
2017-04-12 15:57:01.110049 + 0800 UIImage:0x170285140,{64,64}
2017-04-12 15:57:01.275860 + 0800 UIImage:0x170280910,{64,64}
我有这个:
在.h文件中
- (IBAction)powerButtonAction:(UIButton*)sender;
@property (weak, nonatomic) IBOutlet UIButton *powerButton;
在.m文件中
- (IBAction)powerButtonAction:(UIButton*)sender {
if (sender.selected) {
UIImage *powerButtonImage = [UIImage imageNamed:@"power_off.png"];
[powerButton setImage:powerButtonImage forState:UIControlStateNormal];
[self.view addSubview:powerButton];
NSLog(@"%@",powerButtonImage);
[selectedDevice setPower:powerButton.selected];
sender.selected = NO;
} else {
UIImage *powerButtonImage = [UIImage imageNamed:@"power_on.png"];
[powerButton setImage:powerButtonImage forState:UIControlStateSelected];
[self.view addSubview:powerButton];
NSLog(@"%@",powerButtonImage);
[selectedDevice setPower:!powerButton.selected];
sender.selected = YES;
}
}
答案 0 :(得分:0)
您只需要更改这些行
-(void)viewDidLoad {
UIImage *powerButtonImage = [UIImage imageNamed:@"power_off.png"];
[powerButton setImage:powerButtonImage forState:UIControlStateNormal];
UIImage *powerButtonImage2 = [UIImage imageNamed:@"power_on.png"];
[powerButton setImage:powerButtonImage2 forState:UIControlStateSelected];
[self.view addSubview:powerButton];
}
- (IBAction)powerButtonAction:(UIButton*)sender {
sender.selected = !sender.selected;
}
答案 1 :(得分:0)
答案 2 :(得分:-1)
它认为你应该添加框架
powerButton.frame =CGRectMake(x, y , width, height);