在导航栏中添加彩色图像作为右栏按钮项
Posted
技术标签:
【中文标题】在导航栏中添加彩色图像作为右栏按钮项【英文标题】:Add a colourful image as the right bar button item in a navigation bar 【发布时间】:2016-07-09 15:05:46 【问题描述】:我添加了一个带有彩色背景图像的右侧导航栏项:
let rightButton = UIBarButtonItem(image: UIImage(named: "avatar")!,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
navigationItem.rightBarButtonItem = rightButton
我没有将图像作为按钮的背景(颜色),而是使用白色占位符。
【问题讨论】:
【参考方案1】:您可以将图像的渲染模式更新为
UIImageRenderingMode.alwaysOriginal
.
Swift 4.2:
let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItem.Style.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
斯威夫特 4:
let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
斯威夫特 3:
let img = UIImage(named: "avatar")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
或者,您可以按照弗拉基米尔的回答设置自定义视图。
【讨论】:
对于 Swift 4.2 UIBarButtonItem.Style.plain【参考方案2】:要实现这一点,您需要一个按钮 UIButton
,设置该按钮的图像,然后将其分配为自定义视图,如果您的 UIBarButtonItem
:
let button = UIButton()
button.frame = CGRectMake(0, 0, 51, 31)
button.setImage(UIImage(named: "avatar"), forState: .Normal)
button.addTarget(self, action: #selector(self.rightNavBarItemAction)), forControlEvents: .TouchUpInside)
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.rightBarButtonItem = barButton
【讨论】:
以上是关于在导航栏中添加彩色图像作为右栏按钮项的主要内容,如果未能解决你的问题,请参考以下文章