【问题标题】:Getting the position of my UIBarButtonItem in iOS 11在 iOS 11 中获取我的 UIBarButtonItem 的位置
【发布时间】:2019-01-06 15:36:51
【问题描述】:

在应用启动时,我突出显示了我的一个 BarButtonItem。由于 iOS11 我不能再这样做了,因为我需要以另一种方式初始化它。

首先是我的旧 ios 10 代码。我在初始化 barButtonItemView 后保存了它。

let item1 = UIBarButtonItem(image: UIImage(named: "iconProfile"), style: .plain, target: self, action: #selector(pushSettings))
self.navigationItem.setRightBarButtonItems([item1], animated: true)
if let view = self.navigationItem.rightBarButtonItem?.value(forKey: "view") as? UIView {
    barButtonItemView = view
}

现在我可以通过使用框架来访问 barButtonItem 的位置

barButtonItemView.frame.topMiddle.x

使用 ios 11,我的 UIBarButtonItem 上的图片变小了。我正在阅读我必须通过使用约束来调整它们的大小。所以现在我使用这个函数初始化我的 UIBarButtons:

let imageView = UIImageView(image: UIImage(named: imageName))
imageView.frame = CGRect(x: 5, y: 7, width: 20, height: 20)

let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 30, height: 34)
button.addTarget(self, action: action, for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: 30).isActive = true
button.heightAnchor.constraint(equalToConstant: 34).isActive = true

button.addSubview(imageView)

let barItem = UIBarButtonItem(customView: button)
return barItem

我以同样的方式设置我的 rightBarButtonItem 并尝试以同样的方式获取视图。

self.navigationItem.setRightBarButtonItems([item1], animated: true)
if let view = self.navigationItem.rightBarButtonItem?.value(forKey: "view") as? UIView {
    barButtonItemView = view
}

但这次我的 barButtonItemView 将 x 和 y 值设置为 0,0。有谁知道如何根据屏幕获取 BarButtonItem 的位置?

我尝试了什么

我尝试的第一个解决方案是在尝试再次获取框架之前调用 layoutIfNeeded()。这不起作用,因为 x 和 y 值仍然是 0,0。

【问题讨论】:

  • 您已经使用自定义视图初始化了您的UIBarButtonItem。那么你为什么要尝试使用value(forKey: "view") 再次检索它?只需使用您传递的自定义视图

标签: ios swift


【解决方案1】:

首先,如果您的UIBarButtonItem 只需要显示一个UIImage,您应该使用[UIBarButtonItem initWithImage:style:target:action:] 而不是customView 以获得更标准的布局。如果你想自定义UIBarButtonItem的大小,你可以调整图片大小。

其次,在iOS 10之前,UIBarButtonItem的view是直接添加在UINavigationBar中的,但是在iOS 11之后,UIBarButtonItem是在UIStackView中添加的,而stackView是在UINavigationBar中添加的,所以如果你从customView的frame.origin得到一个(0, 0),表示customView在stackView的(0, 0)原点布局。

第三,UIBarButtonItem 的视图直到 UINavigationBar 被显示并且你的UIBarButtonItem 被放入 bar 时才会被初始化,所以当 UIBarButtonItem 刚刚被初始化时你不能得到视图。也许您可以尝试在 viewController 的 viewWillAppear:viewDidAppear: 中获取视图及其框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 2016-04-27
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多