Search code examples
iosswiftswift3uinavigationcontroller

How to center custom view from xib in navigationItem titleView


I created xib file with center vertical + center horizontal constraints that will be the titleView of navigationItem later. enter image description here

inside the init of the xib I set the text and the image.

class UIViewFromNib: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var titleImageView: UIImageView!
    init(frame: CGRect,title:String,image:UIImage) {
        super.init(frame: frame)
        UINib(nibName: "NavTitle", bundle: nil)
            .instantiate(withOwner: self, options: nil)
        addSubview(view)
        view.frame = self.bounds
        titleLabel.text = title
        titleImageView.image = image
    }
}

Then, inside the videDidLoad I add the view into the titleView of navigationItem.

    let rect = CGRect(x: 0, y: 0, width: width, height: 40)
    let width = self.view.bounds.width
    let view = UIViewFromNib(frame: rect,
                             title:  title,
                             image: image)

    navigationItem.titleView = view
    navigationItem.titleView?.sizeToFit()

but at runtime the view is not in the center. LTR

In RTL even worse

RTL

How can I fix it ? Thanks


Solution

  • Support auto layout.

        let screenWidth = UIScreen.main.bounds.size.width
        let viewWidth = 200.0
        let rect = CGRect(x: (Double)(screenWidth/2)-(Double)(viewWidth/2), y: 0, width: viewWidth, height: 40)