![](/img/trans.png)
[英]How to set constraints on a button in a navigation bar? iOS 13 Swift 5 (Add circular profile image button to navigation controller)
[英]how to add button on navigation bar IOS swift
采用
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
确保您的VC嵌入在UINavigationController中:)
斯威夫特3.0
希望对您有帮助。 并且不要忘记将目标添加到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
像这样添加按钮动作:
func powerButtonTapped(_ sender: UIButton) {
//Do your stuff here
}
您必须将导航项标题视图设置为按钮对象
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
点击时
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
使用UINavigationItem
titleView
属性在导航栏的中心显示titleView
。
自定义视图可以是按钮,因此您需要创建一个UIButton
并将其设置为titleView
。
其他答案中给出了所需的代码,我将向您介绍文档 。 始终最好在实施之前阅读文档。
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.