Creating a Custom UIButton

I want to create a custom UIButton (not a subclass), I would like it to have a background image that will stretch as the width of the UIButton increases. How should I do it?

+3
source share
4 answers

First create a stretchable UIImage(this assumes the “cap” at the end of your button image is 10px):

UIImage *backgroundImage = [[UIImage imageNamed:@"ImageBackground.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];

Then use the stretch image as the background:

[myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];

When you set backgroundImage UIButtonto UIControlStateNormal, it acts as a background for all states unless you explicitly set another backgroundImage for any of the other states.

+15

, UIView contentStretch. , stretchableImageWithLeftCapWidth .

+1

, UIView contentStretch , , , UIButton ( , XCode 4.0.2). IB, - .

0

UIImage, stretchableImageWithLeftCapWidth:topCapHeight:" -Method . :

UIImage *yourBackgroundImage = [[UIImage imageNamed:@"yourImage.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
yourButton.backgroundColor = [UIColor colorWithPatternImage:yourBackgroundImage];
-5

Source: https://habr.com/ru/post/1742656/


All Articles