UIActionSheet+NTESBlock.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // UIActionSheet+NTESBlock.m
  3. // eim_iphone
  4. //
  5. // Created by amao on 12-11-23.
  6. // Copyright (c) 2012年 Netease. All rights reserved.
  7. //
  8. #import "UIActionSheet+NTESBlock.h"
  9. #import <objc/runtime.h>
  10. static char kUIActionSheetBlockAddress;
  11. @implementation UIActionSheet (NTESBlock)
  12. - (void)showInView: (UIView *)view completionHandler: (ActionSheetBlock)block
  13. {
  14. self.delegate = self;
  15. objc_setAssociatedObject(self,&kUIActionSheetBlockAddress,block,OBJC_ASSOCIATION_COPY);
  16. if (view.window)
  17. {
  18. [self showInView:view];
  19. }
  20. else
  21. {
  22. UITabBar *tabbar = [self tabbarForPresent];
  23. if (tabbar)
  24. {
  25. [self showFromTabBar:tabbar];
  26. }
  27. else
  28. {
  29. //如果出现嵌套调用,会出现当前view的window因为被UIActionSheet的attachedWindow出现而置为nil的情况
  30. //所以这种情况下先hack一下
  31. [self performSelector:@selector(showInView:)
  32. withObject:view
  33. afterDelay:1];
  34. }
  35. }
  36. }
  37. - (UITabBar *)tabbarForPresent
  38. {
  39. UITabBar *bar = nil;
  40. UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  41. if (UIInterfaceOrientationIsLandscape(orientation))
  42. {
  43. UIViewController *rootViewController= [[[UIApplication sharedApplication] keyWindow] rootViewController];
  44. if ([rootViewController isKindOfClass:[UITabBarController class]])
  45. {
  46. bar = [(UITabBarController *)rootViewController tabBar];
  47. }
  48. }
  49. return bar;
  50. }
  51. - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
  52. {
  53. ActionSheetBlock block = [objc_getAssociatedObject(self, &kUIActionSheetBlockAddress) copy];
  54. objc_setAssociatedObject(self,&kUIActionSheetBlockAddress,nil,OBJC_ASSOCIATION_COPY);
  55. dispatch_block_t dispatchBlock = ^(){
  56. if (block)
  57. {
  58. block(buttonIndex);
  59. }
  60. };
  61. //需要延迟的原因是actionsheet dismiss本身是个动画,如果在这种动画没完成的情况下直接调用present会导致两个切换冲突
  62. //这种情况在iOS5上最为明显
  63. dispatchBlock();
  64. }
  65. - (void)clearActionBlock
  66. {
  67. self.delegate = nil;
  68. objc_setAssociatedObject(self,&kUIActionSheetBlockAddress,nil,OBJC_ASSOCIATION_COPY);
  69. }
  70. @end