2010-09-22 43 views
5

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

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

回答

5

您需要使用图像自己创建按钮。简单地对各种按钮状态你有兴趣创建一个自定义的UIButton并分配相应的图像。

您可以使用UIImagestretchableImageWithLeftCapWidth方法从设计伸展和使用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]; 
+0

大。这让我走上了正轨。请注意:iOS5中不推荐使用'stretchableImageWithLeftCapWidth:topCapHeight:'。改为使用'resizableImageWithCapInsets:'。 (如链接页面所述) – PEZ 2011-11-30 14:25:08

+0

我想添加我自己的评论,如果你的应用程序支持iOS <5,那么你应该检查'resizableImageWithCapInsets:'选择器是否存在,否则使用已弃用的方法。 – PEZ 2011-12-02 06:59:03