0

What I want to do is change the image when I click on the button. This button works well but the image in my button stays blank. I have done some serious research before posting.

I looked at this first Setting an image for a UIButton in code. While I wasn't sure if my image was nil or not I followed this instruction and this confirms me that my image isn't nil. I even did this and I made sure again that the images where present in the Assets folder.

Here is what I get from my console:

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}

I have this:

In the .h file

- (IBAction)powerButtonAction:(UIButton*)sender;

@property (weak, nonatomic) IBOutlet UIButton *powerButton;

In the .m file

- (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;
   }
}
Community
  • 1
  • 1
F.Chen
  • 31
  • 8

3 Answers3

0

You have to change only these lines

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

}
Yatendra
  • 1,310
  • 1
  • 18
  • 31
  • It is what @Prince suggested and I made the changes but still, the images stays white/blanc. What I find strange it's, that my console shows me that the images are there. {64, 64} is the size of my images. – F.Chen Apr 12 '17 at 09:00
  • @F.Chen if my previous answer not working then try with my new answer once – Yatendra Apr 12 '17 at 09:15
0

You can achieve this using storyBoard

Easiest way

enter image description here

Ravi Panchal
  • 1,285
  • 10
  • 22
-1

it think you should add frame

powerButton.frame =CGRectMake(x, y , width, height);
Return Zero
  • 424
  • 4
  • 15