创建自定义UIButton

Jos*_*hua 3 cocoa-touch uibutton uikit

我希望以编程方式创建自定义UIButton(而不是子类),我希望它有一个背景图像,随着UIButton的宽度增加而拉伸.我该怎么做?

Nic*_*rge 15

首先创建一个可伸缩的UIImage(这假设按钮图像末尾的"上限"为10px):

UIImage *backgroundImage = [[UIImage imageNamed:@"ImageBackground.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
Run Code Online (Sandbox Code Playgroud)

然后使用可伸缩图像作为背景:

[myButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

当您在UIButtonfor 上设置backgroundImage时UIControlStateNormal,它将作为所有状态的背景,除非您为任何其他状态显式设置了不同的backgroundImage.