问题描述
我有一个 UIBarButtonItem
与 UIButton
作为自定义视图.
I have a UIBarButtonItem
with UIButton
as custom view.
UIButton
上有一个 addTarget:action:
.在动作中,我展示了一个弹出框.我目前正在从 sender.frame
(UIButton
的框架)呈现我想从 UIBarButtonItem
呈现.
The UIButton
has a addTarget:action:
on it. In the action I present a popover. I'm currently presenting from the sender.frame
(the UIButton
's Frame) I want to Present from the UIBarButtonItem
instead.
如何从 UIButton
访问 UIBarButtonItem
?
推荐答案
如果您已将 UIButton
设置为 UIBarButtonItem
的 customView
,或者自定义视图的子视图,然后您可以从按钮向上遍历视图层次结构,直到找到包含该按钮的 UIToolbar
或 UINavigationBar
,然后搜索栏的其自定义视图是按钮(或按钮的祖先)的项目.
If you have set your UIButton
as the customView
of a UIBarButtonItem
, or a child of the custom view, then you can walk up the view hierarchy from your button until you find the UIToolbar
or UINavigationBar
that contains the button, then search the bar's items for the one whose custom view is the button (or an ancestor of the button).
这是我完全未经测试的代码.您将调用 [[self class] barButtonItemForView:myButton]
来获取包含您的按钮的项目.
Here's my completely untested code for doing that. You would call [[self class] barButtonItemForView:myButton]
to get the item containing your button.
+ (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;
}
这篇关于UIBarButtonItem 与 UIButton 作为 CustomView - 从 UIButton,如何访问它的 UIBarButtonItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!