UIButton won't go to Aspect Fit in iPhone

后端 未结 21 2171
小鲜肉
小鲜肉 2020-12-23 02:47

I have a couple UIButtons, and in IB they\'re set to Aspect Fit, but for some reason they\'re always stretching. Is there something else you have to set? I tried all the d

21条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 03:17

    This answer is based on @WernerAltewischer's answer.

    To avoid having connect my button to an IBOutlet to execute the code on it, I subclassed UIButton's class:

    // .h
    @interface UIButtonWithImageAspectFit : UIButton
    @end
    
    // .m
    @implementation UIButtonWithImageAspectFit
    
    - (void) awakeFromNib {
        [self.imageView setContentMode:UIViewContentModeScaleAspectFit];
    }
    
    @end
    



    Now create a custom button in your xib, and set its image (not the background image):

    UIButtonWithImageAspectFit: create and set image


    Then, set its class:

    UIButtonWithImageAspectFit: set custom class

    You're done!
    Instead of
    UIButton without image aspect fit
    your button's image aspect fit is now as expected:
    UIButton with image aspect fit

提交回复
热议问题