如何在swift中获取rightbarbuttonItem的框架?我发现了这个:UIBarButtonItem: How can I find its frame?但它说无法将NSString转换为UIView,或者无法将NSString转换为String:
let str : NSString = "view" //or type String
let theView : UIView = self.navigationItem.rightBarButtonItem!.valueForKey("view")//or 'str'
目标是删除rightBarButtonItem,改为添加imageView,并使用fadeOut效果移动它。
由于
答案 0 :(得分:29)
你应该尝试:
var barButtonItem = self.navigationItem.rightBarButtonItem!
var buttonItemView = barButtonItem.valueForKey("view")
var buttonItemSize = buttonItemView?.size
编辑(Swift 3):
var barButtonItem = self.navigationItem.rightBarButtonItem!
let buttonItemView = barButtonItem.value(forKey: "view") as? UIView
var buttonItemSize = buttonItemView?.size
答案 1 :(得分:3)
import UIKit
class ViewController: UIViewController {
let customButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
customButton.setImage(UIImage(named: "myImage"), for: .normal)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: customButton)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(self.customButton.convert(self.customButton.frame, to: nil))
}
}
您必须使用为customView
创建的UIBarButtonItem对象; UIBarButtonItem对象以常规方式创建,没有暴露出足够的信息。在 之后查找框架非常重要 父UINavigationController的UINavigationBar已经完全布局了整个子视图树。对于大多数用例,可见的UIViewController viewDidAppear
是一个很好的近似。
答案 2 :(得分:2)
在Swift4中,XCode9
for view in (self.navigationController?.navigationBar.subviews)! {
if let findClass = NSClassFromString("_UINavigationBarContentView") {
if view.isKind(of: findClass) {
if let barView = self.navigationItem.rightBarButtonItem?.value(forKey: "view") as? UIView {
let barFrame = barView.frame
let rect = barView.convert(barFrame, to: view)
}
}
}
}