How do I prevent a button's background image from stretching?

后端 未结 10 1930
执笔经年
执笔经年 2021-01-30 16:22

I\'m allocating a UIButtonTypeCustom UIButton to a UIView with a background image that is smaller than the button\'s frame. Reason why the image is smaller is because I\'m tryin

10条回答
  •  囚心锁ツ
    2021-01-30 16:58

    A lot of people make the same mistake you do in regards to button images and then jump through hoops trying to make the button behave as they expect it to. Let's clear this up once and for all:

    A UIButton has two types of images it can display -- a foreground image and a background image. The background image for a button is expected to replace the button's background texture. As such, it makes sense that it stretches to fill the entire background. However, the button's foreground image is expected to be an icon that may or may not display alongside text; it will not stretch. It may shrink if the frame is smaller than the image, but it will not stretch. You can even set the alignment of the foreground image using the Control alignment properties in Interface Builder.

    A button's foreground and background image can be set in code like this:

    // stretchy
    [self setBackgroundImage:backgroundImage forState:UIControlStateNormal];  
    
    // not stretchy
    [self setImage:forgroundImage forState:UIControlStateNormal]; 
    

提交回复
热议问题