Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS自定义按钮类似于barbutton_Button_Ios_Uibarbuttonitem - Fatal编程技术网

iOS自定义按钮类似于barbutton

iOS自定义按钮类似于barbutton,button,ios,uibarbuttonitem,Button,Ios,Uibarbuttonitem,我想把按钮放在不同的地方(不是导航栏),它们有动态文本。我希望它们看起来像黑色导航栏按钮项目(灰色和黑色渐变) 我将如何着手创建这些?它们需要是基于按钮文本的动态宽度。我知道我可以创建png文件并拉伸它们,但有没有更好的方法?您需要使用图像自己创建按钮。只需创建一个自定义UIButton,并为您感兴趣的各种按钮状态分配适当的图像 您可以使用UIImage的StretcableImageWithLeftCapWidth方法从设计用于拉伸的图像创建可拉伸图像,并使用NSString的sizeWith

我想把按钮放在不同的地方(不是导航栏),它们有动态文本。我希望它们看起来像黑色导航栏按钮项目(灰色和黑色渐变)


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

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

您可以使用
UIImage
StretcableImageWithLeftCapWidth
方法从设计用于拉伸的图像创建可拉伸图像,并使用
NSString
sizeWithFont
方法确定按钮的大小

:

像这样的事情可能会奏效:

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

伟大的这使我走上了正确的道路。其他人注意:
StretcableImageWithLeftCapWidth:topCapHeight:
在iOS5中已被弃用。改用
大小可调的图像WithCapInsets:
。(如链接页面所述。)我想在我自己的评论中补充一点,如果你的应用程序支持iOS<5,那么你应该检查
resizebleimagewithcapinsets:
选择器是否存在,否则使用不推荐的方法。