UIButton won't go to Aspect Fit in iPhone

后端 未结 21 1980
小鲜肉
小鲜肉 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:04

    This worked for me

    [button.imageView setContentMode:UIViewContentModeScaleAspectFit];
    

    Thanks to @ayreguitar for his comment

    0 讨论(0)
  • 2020-12-23 03:06

    This method worked for me very well.:

    In Xib select the button and set user defined runtime attributes:

    • Key path: self.imageView.contentMode
    • Type: Number
    • Value: 1

    Click here to see more clearly the solution

    We use number because you cant use enum there. But the UIViewContentModeScaleAspectFit is equal to 1.

    0 讨论(0)
  • 2020-12-23 03:06

    If you are doing this in Interface Builder, you can use the Runtime attributes inspector to set this directly without any code.

    Set your Key Path on the button to be "imageView.contentMode" with a type of "Number" and a value of "1" (or whichever mode you would like).

    0 讨论(0)
  • 2020-12-23 03:06

    Use button's imageView for contentMode. Not directly on the button itself.

    homeButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    homeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    homeButton.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    [homeButton setImage:[UIImage imageNamed:kPNGLogo] forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-23 03:06

    UIView content modes apply to the corresponding CALayer's "content". This works for UIImageViews because they set the CALayer content to the corresponding CGImage.

    drawRect: ultimately renders to the layer content.

    A custom UIButton (as far as I know) has no content (the rounded-rect style buttons might be rendered using content). The button has subviews: the background UIImageView, the image UIImageView, and the title UILabel. Setting the contentMode on the subviews may do what you want, but messing around with the UIButton view hierarchy is a bit of a no-no.

    0 讨论(0)
  • 2020-12-23 03:08

    Changing UIButton.imageView.contentMode does not worked for me.
    I solved the problem by setting the image to 'Background' property.
    You can add ratio constraint if you need

    0 讨论(0)
提交回复
热议问题