简体   繁体   中英

centering titleView in navigationItem

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 (ie, 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM