user2893180
user2893180

Reputation: 41

In iOS7.1 UIButton set image not working?

[_firstPrincipleButton setBackgroundImage:[UIImage imageNamed:@"i_press.png"]
                                 forState:UIControlStateNormal];

The above code is working fine in iOS7 but in iOS7.1 this is not changing the image of UIButton. I have also tried to do this with setImage but didn't work.

Thanks

Upvotes: 4

Views: 6202

Answers (2)

Maria
Maria

Reputation: 21

It is a bug in iOS 7.1 ,

you can create a category for UIButton and implement a method to set the image somewhat like this.

-(void)setImage:(UIImage *)image forButtonState:(UIControlState)state
{
  CGFloat version = [[UIDevice currentDevice] systemVersion].floatValue ;
  if( version  <= 7.1)
  {
      BOOL isFirstTime = YES ;
      for(UIView *aView in self.subviews)
      {
          if([aView isKindOfClass:[UIImageView class]])
          {
              [(UIImageView *)aView setImage:image] ;
              isFirstTime = NO ;
              break ;
          }
      }
      if(isFirstTime)
      {
          CGRect frame = self.frame ;
          frame.size = image.size ;
          UIImageView * imageView = [[UIImageView alloc] initWithFrame:frame];
          [imageView setImage:image];
          [self addSubview:imageView];

      }
      
  }
  else
      
    [self setImage:image forState:state];
    
}

This will work.

enjoy coding :)

Upvotes: 0

Flo
Flo

Reputation: 2349

Just in case that others have the same problem and need another hint on how to fix this:

I also had this problem and finally found out that setting a button's (background) image doesn't work on iOS 7.1, if the button is disabled.

Not sure if this fixes your problem, but it was mine. Calling setNeedsLayout didn't help in my case, unfortunately. What you can do as a workaround is either to override UIButton or to add a category that contains a method like the following to set an image:

- (void)setImage:(UIImage *)img forButtonState:(UIControlState)state
{
    BOOL shouldEnable = self.enabled;
    self.enabled = YES;
    [self setImage:img forState:state];
    self.enabled = shouldEnable;
}

Filed a bug report for this issue (16497031).

Upvotes: 9

Related Questions