在Swift中获取UIBarButtonItem的框架?
我怎么能迅速获得rightbarbuttonItem的框架? 我发现这个: UIBarButtonItem:我如何find它的框架? 但它说不能将NSString转换为UIView,或不能将NSString转换为string:
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创build的UIBarButtonItem对象。 创buildUIBarButtonItem对象的常规方式没有足够的信息暴露。 在父UINavigationController的UINavigationBar已经完全布置完整的子视图树之后 ,查找框架是非常重要的。 对于大多数用例来说,可见的UIViewController的viewDidAppear
是一个足够好的近似值。