iOS自定义按钮类似于barbutton

5
我想在各个地方(而不是在导航栏中)放置具有动态文本的按钮。我希望它们看起来类似于黑色导航栏按钮项(带有灰色和黑色渐变)。如何创建这些按钮?它们需要根据按钮文本的长度动态调整宽度。我知道可以创建PNG文件并将其拉伸,但是否有更好的方法?
1个回答

5
你需要使用图片自己创建按钮。只需创建一个自定义 UIButton 并为你感兴趣的各种按钮状态分配适当的图像即可。
你可以使用 UIImage 的 stretchableImageWithLeftCapWidth 方法从设计为拉伸的图像创建可拉伸的图像,并使用 NSString 的 sizeWithFont 方法确定按钮应该有多大。

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];

太好了,这让我找对了方向。提醒其他人:stretchableImageWithLeftCapWidth:topCapHeight:在iOS5中已被弃用。请改用resizableImageWithCapInsets:。(如链接页面所述。) - PEZ
我想在我的评论中补充一点,如果你的应用支持iOS < 5,那么你应该检查是否有resizableImageWithCapInsets:选择器,否则使用已弃用的方法。 - PEZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接