简体   繁体   中英

how to add button on navigation bar IOS swift

My goal is to add a button in the middle of navigation bar

在此处输入图片说明

override func viewDidLoad() {
        super.viewDidLoad()
        // What should I add here?
    }

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 :)

Swift 3.0

hope will help you. And don't forget to add target to 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.

Custom Views can be buttons so you would need to create a UIButton and set it to 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM