我想在导航栏的右侧显示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)
但是它不能解决问题。
根据我的经验,您已经遇到了这个问题,因为您为所有
resolution 1X, 2X and 3X
添加了大尺寸图像。你需要将其缩小到更适合导航栏的大小。
如果要使用相同的图像,则需要在代码中进行以下更改。
您只需要在UIImageView
内添加UIView
,然后将所有内容可以正常工作。
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
您需要将其缩放到更适合导航栏的大小。请查看UINavigationBar
]的图像尺寸
对于1X图像尺寸:24X24
对于2X图像尺寸:48X48
对于3X图像尺寸:72X72
问题是图像的大小。可能太大了。您会注意到,如果您使用系统映像之一,则按钮的位置正确。