I am trying to center my titleView in my navigationItem
.
After localizing my app, I saw this behavior:
This is my code as an extension
to navigationItem
:
extension UINavigationItem{
func makeImg(){
let container = UIView(frame: CGRect(x: 0,y: 0,width: 200,height: 40))
let logo = UIImage(named: "Rookie")
let imageView = UIImageView(frame: CGRect(x: 66.75, y: 7.25, width: 66.5, height: 25.5))
imageView.image = logo
imageView.layer.masksToBounds = true
imageView.clipsToBounds = true
container.addSubview(imageView)
self.titleView = container
}
}
I think it has something to do with my superView in navigationItem. So I should reference the Screens bounds. Any ideas?
This happens if the view set as titleView
is very wide. Views that are added as a titleView
are only resized if their width is wider than the available space, in which case they're resized to fill the space between the left bar button item and the right.
In this case, you've set your container
object as being 200 points wide, which is wider than the available space with both of those items.
If you set the container
width to match the image view (i.e., 66.5 points), then it should become centered. :)
(Or conversely, if you don't plan to add any other views, you can set the image view directly as the titleView
)