Search code examples
iossdwebimage

How to set contentMode when using SDWebImage


I use SDWebImage, here I meet a problem.
I have a ABCButton subclass of UIButton.

@interface ABCButton : UIButton
@property (weak, nonatomic) SAIBanner *banner;
@end
@implementation ABCButton
- (void)setBanner:(SAIBanner *)banner {
    _banner = banner;
    self.contentMode = UIViewContentModeScaleAspectFit;
    [self sd_setImageWithURL:[NSURL URLWithString:banner.bannerPicUrl] forState:UIControlStateNormal placeholderImage:[UIImage     imageNamed:@"default_banner"]];
}
@end   

I found the setContentMode won't work, my question is how to set contentMode of UIButton or UIImageView, when using SDWebImage?


Solution

  • The contentMode is a property from the UIView class. So you can find it in all its subclasses (UIButton, UIImageView...) You want specify how should be adjusted the image so you have to set the contentMode in the button UIImageView property. As a mention before, the button has a contentMode property inherited from UIViewbut isn't the property you need set.

    So you should change:

    self.contentMode
    

    by

    [self imageView].contentMode
    

    Here the complete code:

    @interface ABCButton : UIButton
    @property (weak, nonatomic) SAIBanner *banner;
    @end
    @implementation ABCButton
    - (void)setBanner:(SAIBanner *)banner {
        _banner = banner;
        [self imageView].contentMode = UIViewContentModeScaleAspectFit;
        [self sd_setImageWithURL:[NSURL URLWithString:banner.bannerPicUrl] forState:UIControlStateNormal placeholderImage:[UIImage     imageNamed:@"default_banner"]];
    }
    @end