Why does a custom UIButton image does not resize in Interface Builder?

前端 未结 10 1172
你的背包
你的背包 2020-12-24 00:45

Why does a custom UIButton image not resize with the button?

I set its view mode to Scale to Fill in Interface Builder, but unlike a UIImageView image, it d

相关标签:
10条回答
  • 2020-12-24 01:35

    Remember to set Control Alignment settings for the button

    0 讨论(0)
  • 2020-12-24 01:42

    Try this:

    [button setImage:image forState:UIControlStateNormal];
    button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    

    In Swift:

    button.contentVerticalAlignment = .fill
    button.contentHorizontalAlignment = .fill
    
    0 讨论(0)
  • 2020-12-24 01:43

    Updating this post will full answer for Swift 5:

    //Set button's image
    let image = UIImage(systemName: "heart.fill") //Your image here
    button.setImage(image, for: .normal)
    
    //Optional: Remove background image if you added one on accident
    button.setBackgroundImage(nil, for: .normal)
    
    //Optional: Set button's title (displayed next to button's image)
    button.setTitle(nil, for: .normal)
    
    //The button's "content" includes the title label and image
    //So we set the button's content to fill the button
    //If title label is nil, the content will only show the image
    button.contentVerticalAlignment = .fill
    button.contentHorizontalAlignment = .fill
    
    //Set button's image to desired content mode (aspectFit avoids distortion)
    //This restricts the image from resizing to fill the entire content area
    button.imageView?.contentMode = .scaleAspectFit
    
    0 讨论(0)
  • 2020-12-24 01:46

    Just do (From Design OR From Code):

    From Design

    1. Open your xib OR Storyboard.
    2. Select button
    3. Inside Attribute Inspector (Right side) > In "Control" section > select last 4th option for both Horizontal and Verical.

    [For Point#3: Change Horizontal and vertical Align to UIControlContentHorizontalAlignmentFill and UIControlContentVericalAlignmentFill]

    From Code

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill; button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

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