在iPad上使用UIBarButtonItem关闭UIActionSheet

6

我有一个UIToolbar,里面包含多个UIBarButtonItem,使用showFromBarButtonItem:显示各种UIActionSheet

在iPad上,当其中一个Action Sheet显示在屏幕上时,点击Action Sheet外部的任何地方都会将其移除,不会触发其他操作(例如,点击按钮不会触发按钮)。这是设计上的限制 - 虽然我对此并不满意,但只要这是通常的行为,我就接受它。

但有一种情况例外。如果我点击另一个UIBarButtonItem,那么这个按钮会被触发,而当前的Action Sheet不会从屏幕上移除。如果新按钮启动了另一个UIActionSheet,那么我最终会在屏幕上看到两个(或更多)Action Sheet。

当然,我可以通过繁琐的过程来记住屏幕上的内容并手动关闭它们,但我也关注用户,因为某些点击(即针对工具栏按钮的点击)会被认可,而其他点击则被忽略。

我能做些什么还是必须接受这种情况?

1个回答

2
这确实是一个令人烦恼的不一致之处,但并不难纠正。这个例子假设您只需要显示 UIActionSheets,这似乎是您的情况。
以下是如何修复此问题的示例,从 .h 开始:
@interface TestToolBarExclusiveActionSheet : UIViewController <UIActionSheetDelegate>{
    UIActionSheet *sheetShowing;
}
@property (weak, nonatomic) IBOutlet UIBarButtonItem *oneButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *twoButton;
@end

还有.m文件:

#import "TestToolBarExclusiveActionSheet.h"
@implementation TestToolBarExclusiveActionSheet
@synthesize oneButton;
@synthesize twoButton;
-(IBAction)targetForBothButtons:(UIBarButtonItem *)button{
    if (sheetShowing != nil){
        [sheetShowing dismissWithClickedButtonIndex:[sheetShowing cancelButtonIndex] animated:YES];
        sheetShowing = nil;
    }
    else{ // I am free to act on the button push.
        // Just for demo.. So:
        sheetShowing = [[UIActionSheet alloc] initWithTitle:button.title delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Destroy" otherButtonTitles:nil, nil];
        [sheetShowing showFromBarButtonItem:button animated:YES];
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    sheetShowing = nil;
    // Respond to action sheet like normal
}
-(void)viewDidUnload{
    [self setOneButton:nil];
    [self setTwoButton:nil];
    [super viewDidUnload];
}
@end

最后是一张以iPhone模式显示的.xib截图(用于显示图片大小):

enter image description here

只需连接按钮输出并将两个按钮操作连接到targetForBothButtons:方法即可。

您会发现,如果其中一个操作表正在显示,则按下任何栏按钮都会导致操作表被解除。


谢谢。我担心这是唯一的选择,但我错过了cancelButtonIndex属性,这使事情变得更容易了一些。 - Amiram Stark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接