4 uinavigationbar uikit uibarbuttonitem ios swift
我想在导航栏的右侧显示一个 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
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序时,栏按钮项目位于中间,而不是我想要的右侧。我也尝试过:
navigationItem.setRightBarButton(searchBarButtonItem, animated: true)
Run Code Online (Sandbox Code Playgroud)
但这并不能解决问题。
编辑:我在场景委托中以编程方式添加了 NavigationController,因为我没有使用故事板
根据我的经验,您遇到了这个问题,因为您为所有
resolution 1X, 2X and 3X. 您需要将其缩小到更适合导航栏的尺寸。
您需要将其缩小到更适合导航栏的尺寸。请查看图像尺寸UINavigationBar
对于 1X 图像尺寸:24X24
对于 2X 图像尺寸:48X48
对于 3X 图像尺寸:72X72
如果您想使用相同的图像,那么您需要在代码中进行以下更改。
您只需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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
847 次 |
| 最近记录: |