【问题标题】:How can I get the frame of a UIBarButtonItem?如何获取 UIBarButtonItem 的框架?
【发布时间】:2017-07-04 11:13:24
【问题描述】:

我正在尝试获取 UIBarButtonItem 的框架,它只是继承自 UIBarItem/NSObject。

【问题讨论】:

  • 您提出了一个问题并自己发布了答案......同时......为什么会这样?
  • 我试图在网上找到这个信息,但只是得到过时的信息。我想我会把我的工作发布给其他人,让他们受益。
  • @AnoopVaidya 是fine to answer your own question,只要你坚持 SO 的问答格式。
  • 这就是为什么我确认并指出他的答案。但我不知道他的回答,所以我没有在那里投票:(

标签: objective-c ios cocoa-touch


【解决方案1】:

在 iOS 5.0、5.1 和 6.0 中,使用以下方法。也可以轻松修改此方法以与 UIToolBar 一起使用。

- (UIControl *) findBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    UINavigationBar *toolbar = self.navigationController.navigationBar;
    UIControl *button = nil;
    for (UIView *subview in toolbar.subviews) {
        if ([subview isKindOfClass:[UIControl class]]) {
            for (id target in [(UIControl *)subview allTargets]) {
                if (target == barButtonItem) {
                    button = (UIControl *)subview;
                    break;
                }
            }
            if (button != nil) break;
        }
    }

    return button;
}

用法:

UIControl *barButton = [self findBarButtonItem:myBarButtonItem];
CGRect barButtonFrame = barButton.frame;

【讨论】:

  • 这是解决这个问题的一个聪明方法,但它确实做出了一个可能在未来改变的关键假设。使用此代码的任何人都必须知道,此代码可能会在以后的任何 iOS 更新中中断。小心。
  • 我同意这有点冒险。我在 iOS 5.0、5.1 和 6.0 中对此进行了测试。
【解决方案2】:

这种方式最适合我:

UIView *targetView = (UIView *)[yourBarButton performSelector:@selector(view)];
CGRect rect = targetView.frame;

【讨论】:

  • 我在 iOS 11 上为 targetView 收到 nil
【解决方案3】:

我知道您发布此问题的目的是为了发布您找到的答案。我想我会添加一个替代解决方案,它不会有在未来的 iOS 更新中中断的风险。

如果您使用自定义视图创建UIBarButtonItem,则可以访问UIBarButtonItemcustomView 属性。 customViewframe 将反映其在工具栏或导航栏中的位置。

显然,此解决方案会阻止您使用标准的系统定义按钮。但是您可以使用自己的图像轻松复制它们。

通常,您将使用的自定义视图是带有适当图标图像的UIButton。一个技巧是确保启用按钮的showsTouchWhenHighlighted 属性,以便获得通常的高亮效果。

使用与UIBarButtonItem 相同的目标/操作设置UIButton

【讨论】:

  • 如何获得customView 的框架?我从这个答案开始stackoverflow.com/a/46465148/4833705 并尝试了: (1)guard let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return } ; (2)guard let barView = self.navigationItem.rightBarButtonItem?.value(forKey: "view") as? UIView else { return}; (3)guard let customView = barView.subviews.compactMap({ $0 as? UIButton }).first else { return } : (4) guard let rectInWindow = customView.superview?.superview?.convert(customView.frame, to: keyWindow) else { return } 但它停在 (3)。
  • customView 是一个按钮
【解决方案4】:

这是一种无需求助于无证行为或假设的方法。

不要使用 UIBarButtonSystemItem,而是使用带有自定义视图的 UIBarButtonItem。您可以使用以下技术从 UIBarButtonSystemItem 获取图像:

Use UIBarButtonItem icon in UIButton

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2013-10-04
    • 1970-01-01
    • 2020-10-24
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多