iOS开发-UIActionSheet简单介绍

十度 IOS 2015年12月01日 收藏

UIActionSheet和UIAlertView都是ios系统自带的模态视图,模态视图的一个重要的特性就是在显示模态视图的时候可以阻断其他视图的事件响应。一般情况下我们对UIAlertView使用的比较多,UIActionSheet相对来说情况少一点,偶尔作为一个上拉菜单来展示还是非常有用的。通常如果显示一个模态的视图,可以自定义一个UIViewController,不过里面的内容和动画实现起来工作量还是非常多的。

UIActionSheet介绍

介绍UIActionSheet之前需要简单的看下效果实现:

这是最基本的UIActionSheet,标题和按钮,不过有的时候为了美观可以不用标题,效果看起来是非常赞的,先上代码之后讲解:

 

  1. UIActionSheet *actionSheet = [[UIActionSheet alloc]
  2. initWithTitle:@"博客园"
  3. delegate:self
  4. cancelButtonTitle:@"取消"
  5. destructiveButtonTitle:@"确定"
  6. otherButtonTitles:@"keso", @"FlyElephant",nil];
  7. actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
  8. [actionSheet showInView:self.view];

 

大家可以明显感觉到确定是白底红字,其他的按钮是白底蓝字,因为确定在这里是destructiveButton,相当于销毁就是给用户一个明显的提示,这里的显示是直接在View中显示,当然也有其他的地方显示,调用方法如下:

  1. - (void)showFromToolbar:(UIToolbar *)view;
  2. - (void)showFromTabBar:(UITabBar *)view;
  3. - (void)showFromBarButtonItem:(UIBarButtonItem *)item animated:(BOOL)animated NS_AVAILABLE_IOS(3_2);
  4. - (void)showFromRect:(CGRect)rect inView:(UIView *)view animated:(BOOL)animated NS_AVAILABLE_IOS(3_2);
  5. - (void)showInView:(UIView *)view;

跟大多数控件一下,UIActionSheet也是有代理的,实现UIActionSheetDelegate可以在按钮之后执行自己需要执行的事件:

  1. -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
  2. NSString *result=@"";
  3. switch (buttonIndex) {
  4. case 0:
  5. result=@"确定";
  6. break;
  7. case 1:
  8. result=@"keso";
  9. break;
  10. case 2:
  11. result=@"FlyElephant";
  12. break;
  13. case 3:
  14. result=@"取消";
  15. break;
  16. }
  17.  
  18. UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"测试" message:result delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
  19. [alertView show];
  20. }
  21. -(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonInde{
  22. NSLog(@"didDismissWithButtonIndex-FlyElphant");
  23. }
  24. -(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
  25. NSLog(@"willDismissWithButtonIndex-FlyElphant");
  26. }
  27. -(void)actionSheetCancel:(UIActionSheet *)actionSheet{
  28. NSLog(@"Home键执行此方法");
  29. }

 四个方法都是比较常见的使用,一般情况下只需要调用第一个方法即可,actionSheetCancel网上说的比较少,这个方法一般是点击Home键的时候执行,不是点击取消的按钮的执行,详情可参考文档解释:

  1. // Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
  2. // If not defined in the delegate, we simulate a click in the cancel button

 UIActionSheet的样式默认样式,黑色半透明和黑色不透明三种样式:

  1. typedef NS_ENUM(NSInteger, UIActionSheetStyle) {
  2. UIActionSheetStyleAutomatic = -1, // take appearance from toolbar style otherwise uses 'default'
  3. UIActionSheetStyleDefault = UIBarStyleDefault,
  4. UIActionSheetStyleBlackTranslucent = UIBarStyleBlackTranslucent,
  5. UIActionSheetStyleBlackOpaque = UIBarStyleBlackOpaque,
  6. };

  如果你觉得系统的不爽,可以自定义,完全取决于个人需求~