iOS自定义按钮类似于按钮

sol*_*sol 5 button uibarbuttonitem ios

我想将按钮放在具有动态文本的各个位置(不在导航栏中).我希望它们看起来类似于黑色导航栏按钮项目(灰色和黑色渐变).

我将如何创建这些?它们需要基于按钮文本的动态宽度.我知道我可以创建png文件并拉伸它们,但是有更好的方法吗?

小智 5

您需要使用图像自己创建按钮.只需创建一个自定义UIButton,并为您感兴趣的各种按钮状态指定适当的图像.

您可以使用UIImagestretchableImageWithLeftCapWidth方法从设计伸展和使用的图像创建一个可拉伸的图像NSStringsizeWithFont方法来确定按钮应该是什么样的大小.

http://developer.apple.com/library/ios/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/occ/instm/UIImage/stretchableImageWithLeftCapWidth:topCapHeight:

这样的事情可能会成功:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

int capHeight = 31;
int capWidth = 9;
UIImage *buttonTemplate = [UIImage imageNamed:@"button_template.png"];
UIImage *stretchedButtonImage = [buttonTemplate stretchableImageWithLeftCapWidth:capWidth topCapHeight:capHeight];
[button setBackgroundImage:stretchedButtonImage forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)