UIBarButtonItem: How can I find its frame?

前端 未结 16 838
忘掉有多难
忘掉有多难 2020-12-12 23:17

I have a button in a toolbar. How can I grab its frame? Do UIBarButtonItems not have a frame property?

相关标签:
16条回答
  • 2020-12-13 00:02

    Here's what I'm using in iOS 11 & Swift 4. It could be a little cleaner without the optional but I'm playing it safe:

    extension UIBarButtonItem {
        var view: UIView? {
            return perform(#selector(getter: UIViewController.view)).takeRetainedValue() as? UIView
        }
    }
    

    And usage:

    if let barButtonFrame = myBarButtonItem.view?.frame {
        // etc...
    }
    
    0 讨论(0)
  • 2020-12-13 00:07

    You should do a loop over the subviews and check their type or their contents for identifying. It is not safe to access view by kvo and you cannot be sure about the index.

    0 讨论(0)
  • 2020-12-13 00:07

    You can create a UIBarButtonItem with a custom view, which is a UIButton, then you can do whatever you want. :]

    0 讨论(0)
  • 2020-12-13 00:08

    Oof, lots of rough answers in this thread. Here's the right way to do it:

    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))
        }
    }
    
    0 讨论(0)
  • 2020-12-13 00:11

    Check out this answer: How to apply borders and corner radius to UIBarButtonItem? which explains how to loop over subviews to find the frame of a button.

    0 讨论(0)
  • 2020-12-13 00:12
    -(CGRect) getBarItemRc :(UIBarButtonItem *)item{
        UIView *view = [item valueForKey:@"view"];
        return [view frame];
    }
    
    0 讨论(0)
提交回复
热议问题