简体   繁体   中英

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

I'm doing a tutorial that replicates Twitter's iOS app.

I have a BarButtonItem on the left, an ImageView in the middle, and an array of two BarButtonItems on the right. If the array is only populated with one button, the titleView is centered. If I add the other button, the titleView moves over.

I understand the issue lies with the width of the titleView as shown in the pictures at the end.

    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)] : 后

Thank you!

You can insert a dummy button on the left side of the navigationbar just for balance. Make the button the same size as the searchButton and clear background.

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