rightBarButtonItem 出现在 NavigationBar 的中央

rightBarButtonItem appearing in the centre of NavigationBar

我想在导航栏的右侧显示一个 BarButtomItem。 这就是我所做的:

let imageSearch = UIImage(named: "search")?.withRenderingMode(.alwaysOriginal)
    let searchBarButtonItem = UIBarButtonItem(image: imageSearch, style: .plain, target: self, action: #selector(handleSearch))
    searchBarButtonItem.width = 20
    navigationItem.rightBarButtonItem = searchBarButtonItem

当我 运行 应用程序时,条形按钮项目位于中间,而不是我想要的右侧。 我也试过:

navigationItem.setRightBarButton(searchBarButtonItem, animated: true)

但是并没有解决问题

编辑: 我在场景委托中以编程方式添加了 NavigationController,因为我没有使用故事板

As per my experience, You have faced this issue because you're added large size images for all resolution 1X, 2X and 3X. You need to scale it down to a size more appropriate for the navigation bar.

解法:1

您需要将其缩小到更适合导航栏的大小。请查看 UINavigationBar

的图片尺寸

For 1X image Size: 24X24

For 2X image Size: 48X48

For 3X image Size: 72X72

解法:2

如果您想使用相同的图片,则需要对代码进行以下更改。

你只需要在 UIView 中添加 UIImageView 然后一切 按预期工作。

代码:

    let containerView = UIControl(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
    containerView.addTarget(self, action: #selector(handleSearch), for: .touchUpInside)
    let imageSearch = UIImageView(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30))
    imageSearch.image = UIImage(named: "search")
    containerView.addSubview(imageSearch)                
    let searchBarButtonItem = UIBarButtonItem(customView: containerView)
    searchBarButtonItem.width = 20
    navigationItem.rightBarButtonItem = searchBarButtonItem

问题出在您的图片尺寸上。它可能太大了。您会注意到,如果您使用其中一个系统图像,按钮的位置是正确的。

    let imageSearch = UIImage(systemName: "magnifyingglass")
    let searchBarButtonItem = UIBarButtonItem(image: imageSearch, style: .plain, target: nil, action: nil)
    searchBarButtonItem.width = 20
    navigationItem.rightBarButtonItem = searchBarButtonItem

您需要做的是将图像缩小到合适的尺寸。