iOS navigationItem titleView image and text

5.7k views Asked by At

I want to set the navigationItem's titleView with image and text like the picture below:

enter image description here

How do I achieve that?

More specifically, I am trying to do this in Swift.

1

There are 1 answers

0
aircraft On

The condition, your controller must have its navigation controller:

enter image description here

Using my code I write below, the result is like this:

enter image description here

In your view controller ,try my code below:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    initUI()
}

// MARK: - init

func initUI() {

    let rect:CGRect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 64, height: 64))

    let titleView:UIView = UIView.init(frame: rect)
    /* image */
    let image:UIImage = UIImage.init(named: "01.jpg")!
    let image_view:UIImageView = UIImageView.init(image: image)
    image_view.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
    image_view.center = CGPoint.init(x: titleView.center.x, y: titleView.center.y - 10)
    image_view.layer.cornerRadius = image_view.bounds.size.width / 2.0
    image_view.layer.masksToBounds = true
    titleView.addSubview(image_view)

    /* label */
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 30, width: 64, height: 24))
    label.text = "Hello"
    label.font = UIFont.systemFont(ofSize: 12)
    label.textAlignment = .center
    titleView.addSubview(label)

    self.navigationItem.titleView = titleView

}