gpt4 book ai didi

objective-c - UIBarButtonItem with UIButton as CustomView - 从 UIButton,如何访问它的 UIBarButtonItem?

转载 作者:可可西里 更新时间:2023-11-01 03:27:02 27 4
gpt4 key购买 nike

我有一个 UIBarButtonItemUIButton 作为自定义 View 。

UIButton 上有一个 addTarget:action:。在 Action 中,我展示了一个弹出窗口。我目前正在从 sender.frame(UIButton 的框架)进行展示,我想从 UIBarButtonItem 进行展示。

如何从 UIButton 访问 UIBarButtonItem

最佳答案

如果您已将 UIButton 设置为 UIBarButtonItemcustomView 或自定义 View 的 subview ,那么您可以向上走从按钮开始的 View 层次结构,直到找到包含该按钮的 UIToolbarUINavigationBar,然后在栏的项目中搜索其自定义 View 是按钮(或祖先 View )的项目按钮)。

这是我完全未经测试的代码。您可以调用 [[self class] barButtonItemForView:myButton] 来获取包含您的按钮的项目。

+ (BOOL)ifBarButtonItem:(UIBarButtonItem *)item containsView:(UIView *)view storeItem:(UIBarButtonItem **)outItem {
UIView *customView = item.customView;
if (customView && [view isDescendantOfView:customView]) {
*outItem = item;
return YES;
} else {
return NO;
}
}

+ (BOOL)searchBarButtonItems:(NSArray *)items forView:(UIView *)view storeItem:(UIBarButtonItem **)outItem {
for (UIBarButtonItem *item in items) {
if ([self ifBarButtonItem:item containsView:view storeItem:outItem])
return YES;
}
return NO;
}

+ (UIBarButtonItem *)barButtonItemForView:(UIView *)view {
id bar = view;
while (bar && !([bar isKindOfClass:[UIToolbar class]] || [bar isKindOfClass:[UINavigationBar class]])) {
bar = [bar superview];
}
if (!bar)
return nil;

UIBarButtonItem *item = nil;

if ([bar isKindOfClass:[UIToolbar class]]) {
[self searchBarButtonItems:[bar items] forView:view storeItem:&item];
}

else {
UINavigationItem *navItem = [bar topItem];
if (!navItem)
return nil;
[self ifBarButtonItem:navItem.backBarButtonItem containsView:view storeItem:&item]
|| [self ifBarButtonItem:navItem.leftBarButtonItem containsView:view storeItem:&item]
|| [self ifBarButtonItem:navItem.rightBarButtonItem containsView:view storeItem:&item]
|| ([navItem respondsToSelector:@selector(leftBarButtonItems)]
&& [self searchBarButtonItems:[(id)navItem leftBarButtonItems] forView:view storeItem:&item])
|| ([navItem respondsToSelector:@selector(rightBarButtonItems)]
&& [self searchBarButtonItems:[(id)navItem rightBarButtonItems] forView:view storeItem:&item]);
}

return item;
}

关于objective-c - UIBarButtonItem with UIButton as CustomView - 从 UIButton,如何访问它的 UIBarButtonItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505768/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com