简体   繁体   中英

UIButton backgroundImage versus image

I have UIButtons that I was trying to set the images to aspectFit. However using Storyboards I ran into some difficulty I subclassed UIButton and programatically set the imageViews of the buttons to ScaleAspectFit

#import "UIButtonWithImageAspectFit.h"

@implementation UIButtonWithImageAspectFit

-(void)awakeFromNib{
    [self.imageView setContentMode:UIViewContentModeScaleAspectFit];
}

@end

This worked well and the buttons images display nicely.

However, now I have a need to swap out the images of the button programatically so I tried:

[_firstLetterButton setImage:[UIImage imageNamed:@"2CeadLitir.png"]];

But this does not work so according to advise here I must use:

[_firstLetterButton setBackgroundImage:[UIImage imageNamed:@"2CeadLitir.png"] forState:UIControlStateNormal];

which adds the image as a backgroundImage to the button. Now I have to images in the button.

  1. that is scaled nicely as an image property of the button,
  2. and another that is not scaled nicely as a background image displayed behind.

So I returned to the subclass of UIButton UIButtonWithImageAspectFit and tried to change it so that it sets the contentMode of the backgroundImage rather than the image

But it does not seem to have a backgroundImage property that I can access but according to the documentation it does have

currentBackgroundImage
 Property

However I cannot use the same method setContentMode on that currentBackgroundImage

Any ideas how to get around this?

You need to consider this illustration from Apple web-site. 在此处输入图片说明

It's from Buttons tutorial . In particular this:

State
A button has four states to configure for appearance—default, highlighted, selected, and disabled. And form

UIButton class reference

Discussion
In general, if a property is not specified for a state, the default is to use the UIControlStateNormal value. If the UIControlStateNormal value is not set, then the property defaults to a system value. Therefore, at a minimum, you should set the value for the normal state.

And here is information about different UIControlState:

All this links is must-read for beginner iOS Developer.

Actually the UIButton has a method

- (void)setImage:(UIImage *)image
        forState:(UIControlState)state

so All I needed to do was set the state when setting the image on the UIButton instead of on the UIButton.imageView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM