【问题标题】:Get the frame of UIBarButtonItem in Swift?在 Swift 中获取 UIBarButtonItem 的框架?
【发布时间】:2015-03-11 15:42:09
【问题描述】:

如何快速获得 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,并用fadeOut效果移动它。

谢谢

【问题讨论】:

    标签: ios swift uibarbuttonitem uinavigationitem


    【解决方案1】:

    你应该试试:

    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
    

    【讨论】:

    • 非常感谢,用AnyObject? 到 buttonItemView 可以正常工作
    • 不适用于新的 SDK 和 Xcode 8.3.1 你有替代方案吗?
    • @JVS .valueForKey 返回一个 Any?。转换为 UIView 以使其编译。 var buttonItemSize = (buttonItemView as? UIView).size
    • swift3 这样:让 buttonItemSize = (buttonItemView as!UIView).frame.size
    • 这似乎在针对 iOS 11 的 Xcode 9 beta 6 中被破坏了......还有其他人看到同样的情况吗?
    【解决方案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)
                    }
                }
            }
        }
    

    【讨论】:

    • @Aerox 尝试在 viewDidAppear() 方法中调用它
    • @Aerox 你也可以尝试在viewDidLayoutSubviews 中调用它,但你应该小心避免调用它需要调用它。
    【解决方案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 是一个足够好的近似值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2011-02-28
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多