Reputation: 105
I created xib file with center vertical + center horizontal constraints that will be the titleView of navigationItem later.
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.
In RTL even worse
How can I fix it ? Thanks
Upvotes: 0
Views: 1763
Reputation: 256
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)
Upvotes: 2
Reputation: 4896
Try changing this line:
let rect = CGRect(x: 0, y: 0, width: width, height: 40)
to
let rect = CGRect(x: 0, y: 0, width: 200, height: 40)
The problem is you are giving width of the screen to the view. At run time when back button appears view width changes to (totalWidth - navigationBackButtonWidth) which changes the centre alignment of the images inside it.
Upvotes: 1