添加彩色图像作为导航栏中的右侧栏按钮项
Add a colourful image as the right bar button item in a navigation bar
我添加了一个带有彩色背景图片的右侧导航栏项目:
let rightButton = UIBarButtonItem(image: UIImage(named: "avatar")!,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
navigationItem.rightBarButtonItem = rightButton
我没有将图像作为按钮的背景(彩色),而是使用白色占位符。
为此,您需要一个按钮 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
您可以将图像的渲染模式更新为
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))
Swift 4:
let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
Swift 3:
let img = UIImage(named: "avatar")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
或者,您可以按照 Vladimir 的回答设置自定义视图。
我添加了一个带有彩色背景图片的右侧导航栏项目:
let rightButton = UIBarButtonItem(image: UIImage(named: "avatar")!,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
navigationItem.rightBarButtonItem = rightButton
我没有将图像作为按钮的背景(彩色),而是使用白色占位符。
为此,您需要一个按钮 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
您可以将图像的渲染模式更新为
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))
Swift 4:
let img = UIImage(named: "avatar")!.withRenderingMode(.alwaysOriginal)
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
Swift 3:
let img = UIImage(named: "avatar")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
let rightButton = UIBarButtonItem(image: img,
style: UIBarButtonItemStyle.Plain,
target: self,
action: #selector(self.rightNavBarItemAction))
或者,您可以按照 Vladimir 的回答设置自定义视图。