HUToast.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // HUToast.m
  3. // Pods
  4. //
  5. // Created by jewelz on 16/4/30.
  6. //
  7. //
  8. #import "HUToast.h"
  9. #import "hu_const.h"
  10. const static NSTimeInterval kDefaultDuration = 1.0;
  11. @interface HUToast () {
  12. BOOL _didHiden;
  13. }
  14. @property (nonatomic, weak) UILabel *msgLab;
  15. @end
  16. @implementation HUToast
  17. + (instancetype)toast {
  18. static HUToast *toast = nil;
  19. static dispatch_once_t onceToken;
  20. dispatch_once(&onceToken, ^{
  21. toast = [[self alloc] init];
  22. });
  23. return toast;
  24. }
  25. + (void)showToastWithMsg:(NSString *)msg {
  26. [[HUToast toast] showToastWithMsg:msg];
  27. }
  28. - (instancetype)initWithFrame:(CGRect)frame {
  29. self =[super initWithFrame:frame];
  30. if (self) {
  31. _didHiden = YES;
  32. self.alpha = 0;
  33. self.frame = CGRectMake((kScreenWidth-80)/2, (kScreenHeight-50)/2, 100, 30);
  34. self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
  35. self.layer.cornerRadius = 6;
  36. UILabel *msgLab = [[UILabel alloc] initWithFrame:self.bounds];
  37. msgLab.textColor = [UIColor whiteColor];
  38. msgLab.font = [UIFont systemFontOfSize:13];
  39. msgLab.numberOfLines = 0;
  40. msgLab.textAlignment = NSTextAlignmentCenter;
  41. [self addSubview:msgLab];
  42. _msgLab = msgLab;
  43. }
  44. return self;
  45. }
  46. - (void)showToastWithMsg:(NSString *)msg {
  47. if (!_didHiden) {
  48. return;
  49. }
  50. CGFloat width = [msg sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}].width+16;
  51. self.width = width;
  52. self.msgLab.width = width;
  53. self.msgLab.text = msg;
  54. [self showToast];
  55. }
  56. - (void)showToast {
  57. _didHiden = NO;
  58. UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
  59. [window addSubview:[HUToast toast]];
  60. [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
  61. self.alpha = 1;
  62. } completion:^(BOOL finished) {
  63. [NSTimer scheduledTimerWithTimeInterval:kDefaultDuration target:self selector:@selector(hideToash:) userInfo:nil repeats:NO];
  64. }];
  65. }
  66. - (void)hideToash:(NSTimer *)timer {
  67. [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
  68. self.alpha = 0;
  69. } completion:^(BOOL finished) {
  70. [self removeFromSuperview];
  71. _didHiden = YES;
  72. [timer invalidate];
  73. }];
  74. }
  75. @end