gpt4 book ai didi

ios - rightBarButtonItem 出现在 NavigationBar 的中央

转载 作者:行者123 更新时间:2023-12-01 16:12:28 25 4
gpt4 key购买 nike

我想在导航栏右侧显示一个 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)

但这并没有解决问题。

编辑:我在场景委托(delegate)中以编程方式添加了 NavigationController,因为我没有使用 Storyboard

最佳答案

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

关于ios - rightBarButtonItem 出现在 NavigationBar 的中央,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61342196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com