How we can add additional UILabels to UINavigation

2019-09-12 17:04发布

问题:

I would like to add a cycle view and a label to UINavigation. like this:

I can set a label to my UINavigation by this code:

    if let navigationBar = self.navigationController?.navigationBar {
        let firstFrame = CGRect(x: 300, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
        let firstLabel = UILabel(frame: firstFrame)
        firstLabel.text = "First"

        navigationBar.addSubview(firstLabel)

    }

but I have two problems by this code: 1.how to set x position correctly? (to test I set 300 value, but this value show different position on different screen sizes) 2. how to set a cycle background to this label ?

回答1:

You can add both of the view (red circle) and the label (number 16) programmatically as a subView to the button of the bar button item.

What you should do is:

  • Connect the button as an IBOutlet to its ViewController:

Make sure that the connected component is the UIButton, but NOT UIBarButtonItem.

As you can see, I called it btnMenu.

  • Create your views (red circle and number label) and add it to the btnMenu:

It should be similar to:

import UIKit

class ViewController: UIViewController {
    //...

    @IBOutlet weak var btnMenu: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        //...

        // setup the red circle UIView
        let redCircleView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        redCircleView.backgroundColor = UIColor.red
        redCircleView.layer.cornerRadius = view.frame.size.width / 2

        // setup the number UILabel
        let label = UILabel(frame: CGRect(x: 4, y: 0, width: 20, height: 20))
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 10)
        label.text = "16"

        // adding the label into the red circle
        redCircleView.addSubview(label)

        // adding the red circle into the menu button
        btnMenu.addSubview(redCircleView)

        //...
    }

    //...
}

And that's it!

UIButton is a subclass of UIView, meaning that you can add subviews to it (add​Subview(_:​)).

Output:

Hope this helped.