将更多按钮添加到navigationItem时,如何将我的navigationItem.titleView居中?

时间:2018-06-19 23:57:41

标签: ios swift uinavigationitem

我正在做一个教程,复制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)]

Before

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在导航栏的左侧插入一个虚拟按钮,以保持平衡。使按钮的大小与searchButton相同,并清除背景。