0

I think this is going to be a stupid question, but I can't seem to find the answer. I have a few simple lines of code to put a button in the navigation bar:

UIBarButtonItem *cancelButton=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"button-cancel.png"] style:UIBarButtonItemStylePlain target:self action:@selector(cancelPressed:)];
UINavigationItem *item = [[UINavigationItem alloc] init];
item.leftBarButtonItem = cancelButton;
item.hidesBackButton = YES;
[self.navigationBar pushNavigationItem:item animated:NO];

This button works fine, but it looks like this: enter image description here

Any thoughts?

4

4 回答 4

1

您可能希望使用自定义视图创建条形按钮项,其中自定义视图是UIButton

UIImage *cancelImage = [UIImage imageNamed:@"button-cancel"];
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
cancelButton.frame = (CGRect){CGPointZero, cancelImage.size);
[cancelButton setImage:cancelImage forState:UIControlStateNormal];
UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
于 2013-06-07T22:07:05.680 回答
0

UIBarButtonItem/initWithImage:通常用于制作标志性按钮 - 而不是其中包含文本的按钮。

如果您只想更改常见文本的UIBarButtonItem外观,您只需设置条形按钮项目的背景图像。这样,您不必为每个包含按钮文本的按钮提供图像。

文档:- (void)setBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

您还可以通过在UIBarButtonItem外观代理上调用 setBackgroundImage: 来设置此应用程序范围。

最后,请注意,您可能需要创建一个可调整大小的图像以传递给 setBackgroundImage。这将使您的单个图像适应任何按钮大小。参见UIImage/resizeableImageWithCapInsets:resizingMode:(iOS6) 或UIImage/stretchableImageWithLeftCapWidth:topCapHeight:(pre iOS6)

你当然可以按照@Wain 的建议去做,但也有缺点。一方面,您的新闻处理程序将不再发送 UIBarButtonItem 作为“发送者”。直到您有一个公共处理程序突然需要确定发送者是 UIBarButtonItem 还是 UIButton,或者您想针对此 BarButtonItem 呈现 UIPopoverController(但您只有 UIButton 参考...)之前,这似乎并不多。

于 2013-06-07T22:46:55.460 回答
0

根据 button-cancel.png 的大小设置您的按钮 (cancelButton) 大小。

stopButton.frame = CGRectMake ();

于 2013-06-07T22:05:55.000 回答
0

相反,使用您的图像创建自定义类型 UIButton。将 UIbutton 的目标和选择器设置为您希望栏按钮项执行的操作。然后初始化条形按钮项如下:

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

其中 button 是您的 UIButton 使用所需的图像。

于 2013-06-07T22:06:31.407 回答