UIButton won't go to Aspect Fit in iPhone

后端 未结 21 2267
小鲜肉
小鲜肉 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)
    

提交回复
热议问题