当我向 navigationItem 添加更多按钮时,如何使 navigationItem.titleView 居中?

How can I center my navigationItem.titleView when I add more buttons to the navigationItem?

我正在制作一个复制 Twitter iOS 应用程序的教程。

我左边有一个BarButtonItem,中间有一个ImageView,右边有两个BarButtonItems的数组。如果数组只填充了一个按钮,则 titleView 居中。如果我添加另一个按钮,titleView 就会移动。

我知道问题在于 titleView 的宽度,如最后的图片所示。

    let titleImageView = UIImageView(image: #imageLiteral(resourceName: "title_icon"))
    titleImageView.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
    titleImageView.contentMode = .scaleAspectFit

    navigationItem.titleView = titleImageView

    let followButton = UIButton(type: .system)
    followButton.setImage(#imageLiteral(resourceName: "follow").withRenderingMode(.alwaysOriginal), for: .normal)
    followButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)

    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: followButton)

    let searchButton = UIButton(type: .system)
    searchButton.setImage(#imageLiteral(resourceName: "search").withRenderingMode(.alwaysOriginal), for: .normal)
    searchButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)

    let composeButton = UIButton(type: .system)
    composeButton.setImage(#imageLiteral(resourceName: "compose").withRenderingMode(.alwaysOriginal), for: .normal)
    composeButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)

    // THIS IS THE PROBLEM
    navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: composeButton), UIBarButtonItem(customView: searchButton)]

navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: composeButton)]:

navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: composeButton), UIBarButtonItem(customView: searchButton)]:

谢谢!

为了平衡,您可以在导航栏的左侧插入一个虚拟按钮。使按钮与搜索按钮大小相同,背景清晰。