CountDownView.m 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // CountDownView.m
  3. // BuguLive
  4. //
  5. // Created by 岳克奎 on 16/11/28.
  6. // Copyright © 2016年 xfg. All rights reserved.
  7. //
  8. #import "CountDownView.h"
  9. @implementation CountDownView
  10. #pragma mark mark - init
  11. - (instancetype)initWithCoder:(NSCoder *)aDecoder
  12. {
  13. if (self = [super initWithCoder:aDecoder])
  14. {
  15. // 因没实力化,子控件要在from nib 写
  16. // self.backgroundColor = [UIColor whiteColor];
  17. }
  18. return self;
  19. }
  20. - (void)awakeFromNib
  21. {
  22. [super awakeFromNib];
  23. }
  24. #pragma mark mark - set
  25. - (void)setNumLab:(UILabel *)numLab
  26. {
  27. _numLab = numLab;
  28. }
  29. #pragma mark mark - show CountDownView
  30. //开启定时器,让lab不断的做动画。。如果count =0 那就销毁定时器
  31. + (void)showCountDownViewInLiveVCwithFrame:(CGRect)rect inViewController:(UIViewController *)liveViewController block:(void(^)(BOOL finished))block
  32. {
  33. CountDownView * countdown_View = [[NSBundle mainBundle]loadNibNamed:@"CountDownView" owner:nil options:nil][0];
  34. [liveViewController.view addSubview:countdown_View];
  35. countdown_View.frame = rect;
  36. countdown_View.center = liveViewController.view.center;
  37. countdown_View.secondsCountDown = 4;
  38. // 获得队列
  39. dispatch_queue_t queue =dispatch_get_main_queue();
  40. // 创建一个定时器(dispatch_source_t本质还是个OC对象)
  41. countdown_View.timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
  42. dispatch_time_t start =dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC));
  43. uint64_t interval = (uint64_t)(1.0 *NSEC_PER_SEC);
  44. dispatch_source_set_timer(countdown_View.timer , start, interval,0);
  45. // 设置回调
  46. dispatch_source_set_event_handler(countdown_View.timer, ^{
  47. countdown_View.secondsCountDown--;
  48. countdown_View.numLab.text = [NSString stringWithFormat:@"%d",countdown_View.secondsCountDown];
  49. //加载动画
  50. countdown_View.transform = CGAffineTransformScale(CGAffineTransformIdentity, CGFLOAT_MIN, CGFLOAT_MIN);
  51. [UIView animateWithDuration:1.0
  52. animations:^{
  53. countdown_View.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
  54. }
  55. completion:^(BOOL finished) {
  56. }];
  57. if (countdown_View.secondsCountDown == 1)
  58. {
  59. // 取消定时器
  60. dispatch_cancel(countdown_View.timer);
  61. countdown_View.timer = nil;
  62. // countdown_View.numLab.text = @"GO!";
  63. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  64. [countdown_View removeFromSuperview];
  65. if(block)
  66. {
  67. block(YES);
  68. }
  69. });
  70. }
  71. });
  72. // 启动定时器
  73. dispatch_resume(countdown_View.timer);
  74. }
  75. @end