在 Swift 中获取 UIBarButtonItem 的框架?

Get the frame of UIBarButtonItem in Swift?

如何在 swift 中获取 rightbarbuttonItem 的框架?我发现了这个:UIBarButtonItem: How can I find its frame? 但它说不能将 NSString 转换为 UIView,或者不能将 NSString 转换为字符串:

let str : NSString = "view" //or type String
let theView : UIView = self.navigationItem.rightBarButtonItem!.valueForKey("view")//or 'str'

目标是删除 rightBarButtonItem,添加一个 imageView,并使用淡出效果移动它。

谢谢

你应该这样尝试:

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

在 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)
                }
            }
        }
    }
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 是一个足够好的近似值。