【问题标题】:Figure out UIBarButtonItem frame in window?找出窗口中的 UIBarButtonItem 框架?
【发布时间】:2011-02-28 23:26:53
【问题描述】:

UIBarButtonItem 没有扩展 UIView,所以没有什么像框架属性。

但是有什么方法可以让我获得相对于应用程序UIWindow 的CGRect 框架?

【问题讨论】:

    标签: iphone objective-c cocoa-touch uikit


    【解决方案1】:

    你喜欢使用private APIs 吗?如果是,

    UIView* view = thatItem.view;
    return [view convertRect:view.bounds toView:nil];
    

    当然,在瞄准 AppStore 时没有人想要这个。一个更不可靠的方法,也使用了未记录的特性,但会通过Apple的测试,是循环遍历子视图以查找相应的按钮项。

    NSMutableArray* buttons = [[NSMutableArray alloc] init];
    for (UIControl* btn in theToolbarOrNavbar.subviews)
      if ([btn isKindOfClass:[UIControl class]])
        [buttons addObject:btn];
    UIView* view = [buttons objectAtIndex:index];
    [buttons release];
    return [view convertRect:view.bounds toView:nil];
    

    index 是.items 数组中的条形项的索引,删除所有空白项后。这假设按钮按升序排列,但可能不是。更可靠的方法是排序 buttons 数组以增加.origin.x 值。当然,这仍然假设条形按钮项必须继承 UIControl 类,并且是工具栏/导航栏的直接子视图,这又可能不是。


    如您所见,在处理未记录的功能时存在很多不确定性。但是,您只是想在手指下弹出一些东西对吗? UIBarButtonItem 的.action 可以是表单的选择器:

    -(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event;
    

    注意 event 参数——你可以通过

    获得触摸的位置
    [[event.allTouches anyObject] locationInView:theWindow]
    

    或按钮视图

    [[event.allTouches anyObject] view]
    

    因此,您无需迭代子视图或使用未记录的功能来完成您想做的事情。

    【讨论】:

    • 我忘记了事件参数。这显然是最好的选择。
    • 事件参数ftw。非常感谢。
    • 请注意,如果用户同时点击多个位置,[[event.allTouches anyObject] 将无法正常工作。相反,您希望获得与 UITouchPhaseEnded 状态相对应的触摸,如:for( UITouch* touch in [event allTouches] ) { if( [touch phase] == UITouchPhaseEnded ) { view = [touch view]; } }
    • convertRect: 不再是私有的了
    • 这个答案现在已经 5 岁了。这真的仍然是获取 UIBarButtonItem 框架的唯一方法吗?
    【解决方案2】:

    我没有看到这个选项发布(在我看来它更简单),所以这里是:

    UIView *barButtonView = [barButtonItem valueForKey:@"view"];
    

    【讨论】:

    • valueForKey: 是唯一使用的方法。它不是私有 API。这里所做的只是对 Apple 的实现做出假设,Apple 不保证会保持不变。
    • @Gerard "view" 是这里的私有 API。
    • @bugloaf Apple 似乎对“视图”没有问题,因为我已经随它一起发布了一个应用程序并且根本没有尝试隐藏我在做什么。
    • @Gerard 你只是没有被抓住。 Apple 的筛查工具并非无所不知。
    • @Gerard 我认为我们只是不同意私有 API 的定义。我的定义是 Apple 没有公开记录的任何接口,即使调用该接口的代码恰好编译并且 Apple 没有捕获它。
    【解决方案3】:

    在 iOS 3.2 中,有一种更简单的方法可以从工具栏按钮显示操作表弹出框。只需做这样的事情:

    - (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
    {
     UIActionSheet *popupSheet;
     // Prepare your action sheet
     [popupSheet showFromBarButtonItem:sender animated:YES];
    }
    

    【讨论】:

      【解决方案4】:

      这是我用于我的 WEPopover 项目的实现:(https://github.com/werner77/WEPopover):

      @implementation UIBarButtonItem(WEPopover)
      
      - (CGRect)frameInView:(UIView *)v {
      
          UIView *theView = self.customView;
          if (!theView.superview && [self respondsToSelector:@selector(view)]) {
              theView = [self performSelector:@selector(view)];
          }
      
          UIView *parentView = theView.superview;
          NSArray *subviews = parentView.subviews;
      
          NSUInteger indexOfView = [subviews indexOfObject:theView];
          NSUInteger subviewCount = subviews.count;
      
          if (subviewCount > 0 && indexOfView != NSNotFound) {
              UIView *button = [parentView.subviews objectAtIndex:indexOfView];
              return [button convertRect:button.bounds toView:v];
          } else {
              return CGRectZero;
          }
      }
      @end
      

      【讨论】:

      • 不幸的是,这至少有时不起作用。我有一个以编程方式创建的 UIBarButtonItems,我看到当 customView 设置为非零然后设置为零时,条形按钮项目消失并且 [parentView.subviews objectAtIndex:indexOfView] 崩溃(indexOfView 不少于 subviews.count)。跨度>
      • 我用当前(和有效的)实现编辑了答案
      【解决方案5】:

      只要UIBarButtonItem(和UITabBarItem)不继承自UIView——由于历史原因UIBarItem继承自NSObject——这种疯狂仍在继续(在撰写本文时,iOS 8.2 和计数.. .)

      这个帖子的最佳答案显然是@KennyTM's。别傻了,用私有API找视图吧。

      这是获取origin.x 排序数组的单行Swift 解决方案(如Kenny's answer 建议的那样):

          let buttonFrames = myToolbar.subviews.filter({
              $0 is UIControl
          }).sorted({
              $0.frame.origin.x < $1.frame.origin.x
          }).map({
              $0.convertRect($0.bounds, toView:nil)
          })
      

      数组现在是 origin.x 与 UIBarButtonItem 帧排序。

      (如果你觉得有必要阅读更多关于其他人对 UIBarButtonItem 的挣扎,我推荐 Ash Furrow's 2012 年的博文:Exploring UIBarButtonItem)

      【讨论】:

        【解决方案6】:

        我能够让 Werner Altewischer 的 WEpopover 通过向上传递工具栏和
        UIBar按钮: Mod在WEPopoverController.m中

        - (void)presentPopoverFromBarButtonItem:(UIBarButtonItem *)item toolBar:(UIToolbar *)toolBar
                       permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections 
                                       animated:(BOOL)animated 
        {
            self.currentUIControl = nil;
            self.currentView = nil;
            self.currentBarButtonItem = item;
            self.currentArrowDirections = arrowDirections;
            self.currentToolBar = toolBar;
        
            UIView *v = [self keyView];
            UIButton *button = nil;
        
            for (UIView *subview in toolBar.subviews) 
            {
                if ([[subview class].description isEqualToString:@"UIToolbarButton"])
                {
                    for (id target in [(UIButton *)subview allTargets]) 
                    {
                        if (target == item) 
                        {
                            button = (UIButton *)subview;
                            break;
                        }
                    }
                    if (button != nil) break;
                }
            }
        
            CGRect rect = [button.superview convertRect:button.frame toView:v];
        
            [self presentPopoverFromRect:rect inView:v permittedArrowDirections:arrowDirections animated:animated];
        }
        

        【讨论】:

          【解决方案7】:
          -(CGRect) getBarItemRc :(UIBarButtonItem *)item{
              UIView *view = [item valueForKey:@"view"];
              return [view frame];
          }
          

          【讨论】:

            【解决方案8】:

            您可以从 UINavigationBar 视图中获取它。 navigationBar 是一个 UIView,它有 2 或 3 个自定义 subviews 用于栏上的部分。

            如果您知道 UIBarButtonItem 当前显示在右侧的导航栏中,则可以从导航栏的子视图数组中获取其框架。

            首先你需要navigationBar,你可以从navigationController获得,你可以从UIViewController获得。然后找到最右边的子视图:

            UINavigationBar* navbar = curViewController.navigationController.navigationBar;
            UIView* rightView = nil;
            
            for (UIView* v in navbar.subviews) {
               if (rightView==nil) {
                  rightView = v;
               } else if (v.frame.origin.x > rightView.frame.origin.x) {
                  rightView = v;  // this view is further right
               }
            }
            // at this point rightView contains the right most subview of the navbar
            

            这段代码我还没编译所以YMMV。

            【讨论】:

              【解决方案9】:

              这不是最好的解决方案,从某些角度来看,这不是正确的解决方案,我们不能像 follow 一样做,因为我们会隐式访问 UIBarBattonItem 内的对象,但您可以尝试执行以下操作:

              UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
              [button setImage:[UIImage imageNamed:@"Menu_Icon"] forState:UIControlStateNormal];
              [button addTarget:self action:@selector(didPressitem) forControlEvents:UIControlEventTouchUpInside];
              UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
              self.navigationItem.rightBarButtonItem = item;
              
              CGPoint point = [self.view convertPoint:button.center fromView:(UIView *)self.navigationItem.rightBarButtonItem];
              //this is like view because we use UIButton like "base" obj for 
              //UIBarButtonItem, but u should note that UIBarButtonItem base class
              //is NSObject class not UIView class, for hiding warning we implicity
              //cast UIBarButtonItem created with UIButton to UIView
              NSLog(@"point %@", NSStringFromCGPoint(point));
              

              结果我得到了下一个:

              点 {289, 22}

              【讨论】:

              • 使用点击动作中的事件参数仍然是获取点击发生时帧的最安全方法。但是,如果您需要在不检测点击的情况下找出框架,我会说这是一个很好的解决方案如果您检查 rightBarButtonItem 的 respondsToSelector。
              【解决方案10】:

              在实现此代码之前,请务必在您的 Applition 委托 application:didFinishLaunchingWithOptions: 方法中调用 [window makeKeyAndVisible]!

              - (void) someMethod
              {
                  CGRect rect = [barButtonItem convertRect:barButtonItem.customview.bounds toView:[self keyView]];
              }
              
              - (UIView *)keyView {
              UIWindow *w = [[UIApplication sharedApplication] keyWindow];
              if (w.subviews.count > 0) {
                  return [w.subviews objectAtIndex:0];
              } else {
                  return w;
              }
              }
              

              【讨论】:

              • UIBarButtonItem 实例没有 bounds 属性。
              • 代码没有访问 barButtonItem 的边界。它正在访问 barButtonItem 内的自定义视图的边界。
              【解决方案11】:

              我是这样处理的:

              - (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
              {
                  UIView* view = [sender valueForKey:@"view"]; //use KVO to return the view
                  CGRect rect = [view convertRect:view.bounds toView:self.view];
                  //do stuff with the rect
              }
              

              【讨论】:

              • "-valueForKey: 是一种记录在案的公共方法。KVC API 提供了一种防止直接实例变量访问的方法,因此如果该值是可访问的,则不采取任何措施来禁止访问。一个问题可能会在未来版本的 iOS 中遇到未定义的值。为了解决这个问题,您可以将调用包装在 try-block 中。此外,即使您觉得无法在以 App Store 为目标的应用程序中使用它,这并不意味着针对越狱设备的人不能在他们的应用程序中使用这种方法。”用户@jeremy-w-sherman 在另一篇文章中写道
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-03-09
              • 2012-02-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多