【发布时间】: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")再次检索它?只需使用您传递的自定义视图