UIButton won't go to Aspect Fit in iPhone

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

    I had this problem a while back. The issue I had was i was trying to apply this effect to the background UIButton which is limited and therefore means you cannot adjust it as easy.

    The trick is to set it as just an image then apply @ayreguitar's technique and that should fix it!

    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [myButton setContentMode:UIViewContentModeScaleAspectFill];
    [myButton setImage:@"myImage.png" forState:UIControlStateNormal];
    
    0 讨论(0)
  • 2020-12-23 03:22

    Here's an alternative answer in swift:

    myButton.imageView?.contentMode = .ScaleAspectFit
    
    0 讨论(0)
  • 2020-12-23 03:25

    The solution is to set the contentMode on the imageView property of the UIButton. The UIButton has to be created with custom type for this to work I believe (otherwise nil is returned for this property).

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

    ios 12. You need to add also the content Alignment

    class FitButton: UIButton {
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
    
        }
    
        override func layoutSubviews() {
            self.imageView?.contentMode = .scaleAspectFill
            self.contentHorizontalAlignment = .fill
            self.contentVerticalAlignment = .fill
            super.layoutSubviews()
    
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-23 03:28

    I've had that problem before. I solved it by putting my image in a UIImageView, where contentMode settings actually work, and putting a transparent custom UIButton over top of that.

    EDIT: This answer is obsolete. See @Werner Altewischer's answer for the correct answer in modern versions of iOS.

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

    Similar to @Guillaume, I have created a subclass of UIButton as a Swift-File. Then set my custom class in the Interface Builder:

    .

    And here the Swift file:

    import UIKit
    
    class TRAspectButton : UIButton {
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.imageView?.contentMode = .ScaleAspectFit
        }
    }
    
    0 讨论(0)
提交回复
热议问题