![](/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.