UIAlertView+WX.mm 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. //
  2. // UIAlertView+WX.m
  3. // SDKSample
  4. //
  5. // Created by liuyunxuan on 2017/2/10.
  6. //
  7. //
  8. #import "UIAlertView+WX.h"
  9. #import <objc/runtime.h>
  10. static const void *WXAlertSureKey = &WXAlertSureKey;
  11. static const NSInteger kSureTag = 1010;
  12. static const NSInteger kRequestTag = 1020;
  13. @implementation UIAlertView (WX)
  14. /// withOut delegate
  15. + (void)requestWithTitle:(NSString *)title
  16. message:(NSString *)message
  17. defaultText:(NSString *)defaultText
  18. sure:(WXAlertSureBlock)sure;
  19. {
  20. UIAlertView *view = [[UIAlertView alloc] initWithTitle:title
  21. message:message
  22. delegate:nil
  23. cancelButtonTitle:@"取消"
  24. otherButtonTitles:@"确认", nil];
  25. view.delegate = view;
  26. view.alertViewStyle = UIAlertViewStylePlainTextInput;
  27. [view setSureBlock:sure];
  28. [view textFieldAtIndex:0].text = defaultText;
  29. view.tag = kRequestTag;
  30. [view show];
  31. }
  32. + (void)showWithTitle:(NSString *)title
  33. message:(NSString *)message
  34. sure:(WXAlertSureBlock)sure
  35. {
  36. UIAlertView *view = [[UIAlertView alloc] initWithTitle:title
  37. message:message
  38. delegate:nil
  39. cancelButtonTitle:@"取消"
  40. otherButtonTitles:@"确认", nil];
  41. view.delegate = view;
  42. view.tag = kSureTag;
  43. [view setSureBlock:sure];
  44. [view show];
  45. }
  46. #pragma mark - delegate
  47. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  48. {
  49. if (buttonIndex == alertView.cancelButtonIndex)
  50. {
  51. return;
  52. }
  53. WXAlertSureBlock sureBlock = [self sureBlock];
  54. if (alertView.tag == kRequestTag)
  55. {
  56. if (sureBlock)
  57. {
  58. sureBlock(alertView,[alertView textFieldAtIndex:0].text);
  59. }
  60. }
  61. else if (alertView.tag == kSureTag)
  62. {
  63. if (sureBlock)
  64. {
  65. sureBlock(alertView,nil);
  66. }
  67. }
  68. }
  69. #pragma mark - private method
  70. -(void)setSureBlock:(WXAlertSureBlock)block
  71. {
  72. objc_setAssociatedObject(self, WXAlertSureKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  73. }
  74. -(WXAlertSureBlock)sureBlock
  75. {
  76. return objc_getAssociatedObject(self, WXAlertSureKey);
  77. }
  78. @end