【问题标题】:How to set the image on rightBarButtonItem of UINavigationBar?如何在 UINavigationBar 的 rightBarButtonItem 上设置图像?
【发布时间】:2011-07-23 18:26:48
【问题描述】:

我正在尝试在 rightBarButtonItem 上设置图像并且它很好,但唯一错误的是该图像背后的背景比我的图像宽度更大。 任何人都知道如何解决这个问题。 代码:

[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"action_btn.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(actionButtonClicked:)] animated:YES];

【问题讨论】:

  • 尝试增加你的图片宽度......
  • 我不能让图像变形。
  • 有可能。您可以查看我的回答如下。

标签: iphone objective-c uinavigationbar


【解决方案1】:

这里可以在 NavigationBar 的 rightBarButtonItem 上设置图片如下:

UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,105,30);
[button1 setBackgroundImage:[UIImage imageNamed: @"image1.png"] forState:UIControlStateNormal];
[button1 addTarget:appDelegate action:@selector(Open_Link1) forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
[button1 release];

如果您还有其他问题,请告诉我。

【讨论】:

  • 在这里你可以试试这个,它对我有用,我相信一定会为你工作,当它工作时你可以采取必要的行动。
  • 感谢您的行动。如果您需要更多帮助,请告诉我。
【解决方案2】:

Swift 中:

let infoImage = UIImage(named: "my-icon")
let imgWidth = infoImage?.size.width
let imgHeight = infoImage?.size.height
let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
button.setBackgroundImage(infoImage, forState: .Normal)
button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)

附: UIBarButtonItem(image:style:target:action:) 构造函数仅适用于透明 PNG,我还必须设置 clearColor 以外的按钮 tintcolor。

【讨论】:

    【解决方案3】:

    我现在不在 XCode 中,所以我不能发布代码。 流程是这样的

    1. 使用默认初始化程序创建 UIBarButtonItem
    2. 创建 UIImage
    3. 从图像尺寸中获取 CGRect,
    4. 将 UIBarButtonItem.frame 设置为该尺寸

    如果不匹配 100%,请考虑在设置按钮的框架之前将按钮的边界添加到图像尺寸

    【讨论】:

    • 我没有看到任何属性来设置这个按钮的框架。一点点代码会很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多