我一直在寻找这个解决方案一段时间但没有得到任何解决方案 . 例如,一种解决方案
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: nil), animated: true)
此代码将添加一个带有"stop"图像的按钮 . 就像这样,还有其他解决方案"search, "刷新“等等_但是 what if I want to add a button programmatically with the image I want?
8 回答
Custom button image without setting button frame:
您可以使用
init(image: UIImage?, style: UIBarButtonItemStyle, target: Any?, action: Selector?)
使用指定的图像和其他属性初始化新项目 .检查一下Apple Doc. reference
UIBarButtonItem使用按钮框架自定义按钮图像
FOR Swift 3.0
FOR Swift 2.0 and older
For System UIBarButtonItem
For set more then 1 items use rightBarButtonItems or for left side leftBarButtonItems
Using setLeftBarButtonItem or setRightBarButtonItem
只需使用customView设置
UIBarButtonItem
即可例如:
或使用
setFunction
:我只是偶然发现了这个问题,这里是Swift 3和iOS 10的更新:
它肯定比使用所有属性创建UIButton然后随后将customView添加到UIBarButtonItem快得多 .
如果你想将图像的颜色从默认的蓝色更改为例如白色,您可以随时更改色调颜色:
PS你显然应该改变你的应用程序的选择器等:)
Swift 4
或Swift 4.2
更容易在
ViewDidLoad
方法中,定义您的按钮并将其添加到导航栏 .那么你需要定义你在action参数中提到的函数,如下所示
您需要添加
@objc
前缀,因为它仍在使用遗留内容(目标C) .在快捷方式3中,在按钮中执行操作:
我有同样的问题,我已经阅读了另一个主题的答案,然后我解决了另一个类似的方式 . 我不知道哪个更有效 . similar issue
使用原始图像设置LeftBarButton .