我想在导航栏的右侧显示一个 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,因为我没有使用故事板
根据我的经验,您遇到了这个问题,因为您为所有内容添加了大尺寸图像resolution 1X, 2X and 3X
。你需要
将其缩小到更适合导航栏的尺寸。
解决方法:1
您需要将其缩小到更适合导航栏的尺寸。请查看图像尺寸UINavigationBar
对于 1X 图像尺寸:24X24
对于 2X 图像尺寸:48X48
对于 3X 图像尺寸:72X72
解决方案:2
如果您想使用相同的图像,那么您需要在代码中进行以下更改。
你只需要添加UIImageView
在 - 的里面UIView
然后一切
按预期工作。
Code:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)