UIBarButtonItem: How can I find its frame?

前端 未结 16 837
忘掉有多难
忘掉有多难 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:13

    Here's the way to do it:

    -(CGRect)findFrameOfBarButtonItem{
        for (UIView *view in self.navigationController.navigationBar.subviews)
        {
           if ([view isKindOfClass:NSClassFromString(@"_UINavigationBarContentView")])
           {
             UIView * barView = [self.navigationItem.rightBarButtonItem valueForKey:@"view"];
             CGRect barFrame = barView.frame;
             CGRect viewFrame = [barView convertRect:barFrame toView:view];
             return viewFrame;
           }
        }
    
        return CGRectZero;
    }
    
    0 讨论(0)
  • 2020-12-13 00:14

    I used a view on the bar button item with a tag on the view:

    for view in bottomToolbar.subviews {
       if let stackView = view.subviews.filter({$0 is UIStackView}).first {
           //target view has tag = 88
           if let targetView = stackView.subviews.filter({$0.viewWithTag(88) != nil}).first {                                
              //do something with target view
       }
    }
    

    }

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

    Swift 4 up The current best way to do it is to access its frame from :

    self.navigationItem.rightBarButtonItems by

    let customView = navigationItem.rightBarButtonItems?.first?.customView // access the first added customView
    

    Accessing this way is safer than accessing private api.

    • check out the answer in this :

    After Add a CustomView to navigationItem, CustomView always return nil

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

    This way works best for me:

    UIView *targetView = (UIView *)[yourBarButton performSelector:@selector(view)];
    CGRect rect = targetView.frame;
    
    0 讨论(0)
提交回复
热议问题