[英]how to add button on navigation bar IOS swift
Use 采用
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button.setImage(UIImage(named: "ur_image.png"), for: .normal)
self.navigationItem.titleView = button
Make sure your VC is embedded in UINavigationController :) 确保您的VC嵌入在UINavigationController中:)
Swift 3.0 斯威夫特3.0
hope will help you. 希望对您有帮助。 And don't forget to add target to
UIButton
. 并且不要忘记将目标添加到
UIButton
。
let headerView = UIButton.init(frame: CGRect(x: 0, y: 0, width: 30, height: 25))
headerView.setImage(UIImage(named: "btn_image.png"), for: .normal)
headerView.addTarget(self, action: #selector(self.powerButtonTapped(_:)), for: .touchUpInside)
self.navigationItem.titleView = headerView
Add button action like this: 像这样添加按钮动作:
func powerButtonTapped(_ sender: UIButton) {
//Do your stuff here
}
You have to set navigation item title view to your button object 您必须将导航项标题视图设置为按钮对象
let powerButton = UIButton(type: .custom)
powerButton.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
powerButton.setImage(UIImage(named: "power.png"), for: .normal)
powerButton.addTarget(self, action: #selector(self.clickOnPowerButton), for: .touchUpInside)
self.navigationItem.titleView = powerButton
When clicking 点击时
func clickOnPowerButton(button: UIButton) {
// do your stuffs
}
let imageView = UIImageView(image: UIImage(named: "myImage"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
Use titleView
property of UINavigationItem
to display a customview in the center of the navigation bar. 使用
UINavigationItem
titleView
属性在导航栏的中心显示titleView
。
Custom Views can be buttons so you would need to create a UIButton
and set it to titleView
. 自定义视图可以是按钮,因此您需要创建一个
UIButton
并将其设置为titleView
。
Code required for this is given in other answers, I would point you to the documentation . 其他答案中给出了所需的代码,我将向您介绍文档 。 It is always better to read documentation before implementation.
始终最好在实施之前阅读文档。
let lButton = UIButton()
lButton.setTitle("Test Button", for: .normal)
lButton.frame = CGRect(x:20, y: 0, width: self.view.frame.size.width - 50, height: 50)
lButton.backgroundColor = UIColor.green
lButton.setTitleColor(UIColor.red, for: .normal)
lButton.addTarget(self, action: #selector(self.locationChangeAction), for: .touchUpInside)
self.navigationController?.navigationBar.addSubview(lButton)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.