Get the frame of UIBarButtonItem in Swift?

后端 未结 3 1765
长情又很酷
长情又很酷 2020-12-06 09:44

how could I get the frame of a rightbarbuttonItem in swift? I found this : UIBarButtonItem: How can I find its frame? but it says cannot convert NSString to UIView, or canno

3条回答
  •  我在风中等你
    2020-12-06 10:27

    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))
        }
    }
    

    You must use UIBarButtonItem objects created with customView for this; UIBarButtonItem objects created the regular way don't have enough information exposed. It's important that the frame be looked up after the parent UINavigationController's UINavigationBar has completely laid out its entire subview tree. For most use cases, the visible UIViewController's viewDidAppear is a good enough approximation of this.

提交回复
热议问题