UIAlertView+NTESBlock.m 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // UIAlertView+NTESBlock.m
  3. // eim_iphone
  4. //
  5. // Created by amao on 12-11-7.
  6. // Copyright (c) 2012年 Netease. All rights reserved.
  7. //
  8. #import "UIAlertView+NTESBlock.h"
  9. #import <objc/runtime.h>
  10. static char kUIAlertViewBlockAddress;
  11. @implementation UIAlertView (NTESBlock)
  12. - (void)showAlertWithCompletionHandler: (void (^)(NSInteger))block
  13. {
  14. self.delegate = self;
  15. objc_setAssociatedObject(self,&kUIAlertViewBlockAddress,block,OBJC_ASSOCIATION_COPY);
  16. [self show];
  17. }
  18. - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
  19. {
  20. AlertBlock block = objc_getAssociatedObject(self, &kUIAlertViewBlockAddress);
  21. if (block)
  22. {
  23. block(buttonIndex);
  24. objc_setAssociatedObject(self, &kUIAlertViewBlockAddress, nil, OBJC_ASSOCIATION_COPY);
  25. }
  26. }
  27. - (void)clearActionBlock
  28. {
  29. self.delegate = nil;
  30. objc_setAssociatedObject(self, &kUIAlertViewBlockAddress, nil, OBJC_ASSOCIATION_COPY);
  31. }
  32. @end
  33. @implementation UIAlertController (NTESBlock)
  34. - (UIAlertController *)addAction:(NSString *)title
  35. style:(UIAlertActionStyle)style
  36. handler:(void (^ __nullable)(UIAlertAction *action))handler
  37. {
  38. UIAlertAction *action = [UIAlertAction actionWithTitle:title style:style handler:handler];
  39. [self addAction:action];
  40. return self;
  41. }
  42. - (void)show
  43. {
  44. UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
  45. [vc presentViewController:self animated:YES completion:nil];
  46. }
  47. @end