创建操作表(UIActionSheet)

UIActionSheet用来创建一个操作表,它的初始化代码如下:

- (IBAction)testActionSheet:(id)sender 
{
UIActionSheet *actionSheet = [[UIActionSheet alloc] 
initWithTitle:@"选择操作" 
delegate:self 
cancelButtonTitle:@"取消操作" 
destructiveButtonTitle:@"清空数据(无法恢复)" 
otherButtonTitles:@"保存数据", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
//[actionSheet showInView:self.view];
[actionSheet showFromRect:[(UIButton *)sender frame] inView:self.view animated:YES];
}

调用该方法后,会产生如下界面:

参数说明:
initWithTitle --- 初始化操作表并设置出现在操作表顶端的标题
delegate --- 指定将作为操作表委托的对象。如果不需要响应任何操作,可设置为nil
cancelButtonTitle --- 操作表中默认按钮的标题
destructiveButtonTitle --- 显示一个破坏性按钮,该按钮呈亮红色显示,一般用来提示将导致信息丢失的操作。如果设置为nil,将不会显示
otherButtonTitles --- 操作表中额外按钮的标题,是一个数组,以nil结尾

actionSheet.actionSheetStyle用来定义操作表的外观,有4种样式可供选择:
UIActionSheetStyleDefault --- 由iOS决定的操作表默认外观
UIActionSheetStyleAutomatic --- 如果屏幕底部有按钮栏,则采用与按钮栏匹配的样式
UIActionSheetStyleBlackOpaque --- 不透明的深色样式
UIActionSheetStyleBlackTranslucent --- 半透明的深色样式

显示操作表与显示提醒视图不同,操作表可与给定的视图、选项卡栏或工具栏相关联。操作表出现在屏幕上时,将以动画方式展示它与这些元素的关系。

[actionSheet showInView:self.view]是在当前控制器的视图打开操作表。如果有工具栏或选项卡栏,可使用方法showFromToolbar或showFromTabBar让操作表看起来是从这些用户界面元素中打开的。

响应操作类必须遵守协议UIActionSheetDelegate并实现方法actionSheet:clickedButtonAtIndex。

首先在类的头文件(.h)里声明为遵守UIAlertViewDelegate协议:

@interface ViewController : UIViewController <UIAlertViewDelegate>

然后实现方法actionSheet:clickedButtonAtIndex:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *strTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
NSLog(@"button title is %@",strTitle);
NSLog(@"cancel button's index is %d",[actionSheet cancelButtonIndex]);
NSLog(@"destructive button's index is %d",[actionSheet destructiveButtonIndex]);
}

在iPad中,不应在视图上显示操作表。Apple用户界面指南指出,必须在弹出框中显示操作表。弹出框(popover)是一种独特的用户界面元素,在用户触摸某个屏幕元素时出现,并通常在用户触摸背景时候消失。弹出框还包含一个小箭头,指向触发它的UI元素。为符合Apple的要求,即操作表必须显示在弹出框中,可使用方法showFromRect:inView:animated来显示一个包含操作表的弹出框。其中第一个参数(showFromRect)指定了屏幕上的一个矩形区域,弹出框的箭头将指向它。为正确设置该参数,可使用sender变量(这里是一个UIButton对象)的frame属性。参数inView指定了操作表/弹出框将显示在其中的视图(这里设置为self.view)。而参数animated是一个布尔值,指定是否以动画方式显示。

当您在iPad上运行该应用程序时,操作表将包含在一个弹出框中;而在iPhone上运行时,将忽略额外的参数,就像使用方法showInView那样显示操作表。

对于操作表,需要指出的最后一点是,当您在iPad上弹出框中显示操作表时,将自动忽略取消按钮。这是因为触摸弹出框的外面与单击取消按钮的效果相同,因此这个按钮是多余的。

原文地址:https://www.cnblogs.com/CoderWayne/p/3596747.html