UIButton won't go to Aspect Fit in iPhone

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

    Combining together a few different answers into one solution-- create a button with a custom type, set the button's imageView contentMode property, and set the image for the button (not the background image, which will still scale to fill).

    //Objective-C:
    UIImage *image = [UIImage imageNamed:"myImageName.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    //Swift:
    let image = UIImage(named: "myImageName.png")
    let button = UIButton(type: .custom)
    button.imageView?.contentMode = .scaleAspectFit
    button.setImage(image, for: .normal)
    
    0 讨论(0)
  • 2020-12-23 03:30

    I had problems with the image not resizing proportionately so the way I fixed it was using edge insets.

    fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
    
    0 讨论(0)
  • 2020-12-23 03:30

    This overlaps many of the other answers, but the solution for me was to

    • set the contentMode of the UIImageView for the button to .ScaleAspectFit – which can either be done in the ”User Defined Runtime Attributes” in Interface Builder (ie. self.imageView.contentMode, Number, 1) or in a UIButton subclass;
    • disable ”Autoresize Subviews”;
    • set ”Edge” to ”Image” and appropriate ”Top” and ”Bottom” values for ”Inset” (which might only be needed if you, like me, used a PDF as image).
    0 讨论(0)
提交回复
热议问题