TGWebProgressLayer.m 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. //
  2. // TGWebProgressLayer.m
  3. // TGWebViewController
  4. //
  5. // Created by 赵群涛 on 2017/9/19.
  6. // Copyright © 2017年 QR. All rights reserved.
  7. //
  8. #import "TGWebProgressLayer.h"
  9. #import <UIKit/UIKit.h>
  10. #import "NSTimer+addition.h"
  11. static NSTimeInterval const ProgressTimeInterval = 0.03;
  12. @interface TGWebProgressLayer()
  13. @property (nonatomic, strong) CAShapeLayer *layer;
  14. @property (nonatomic, strong) NSTimer *timer;
  15. @property (nonatomic, assign) CGFloat plusWidth;
  16. @end
  17. @implementation TGWebProgressLayer
  18. - (instancetype)init {
  19. self = [super init];
  20. if (self) {
  21. [self initBezierPath];
  22. }
  23. return self;
  24. }
  25. - (void)initBezierPath {
  26. //绘制贝塞尔曲线
  27. UIBezierPath *path = [UIBezierPath bezierPath];
  28. //起点
  29. [path moveToPoint:CGPointMake(0, 3)];
  30. //终点
  31. [path addLineToPoint:CGPointMake(WIDTH,3)];
  32. self.path = path.CGPath;
  33. self.strokeEnd = 0;
  34. _plusWidth = 0.005;
  35. self.lineWidth = 2;
  36. self.strokeColor = [UIColor redColor].CGColor;
  37. _timer = [NSTimer scheduledTimerWithTimeInterval:ProgressTimeInterval target:self selector:@selector(pathChanged:) userInfo:nil repeats:YES];
  38. [_timer tg_pauseTime];
  39. }
  40. // 设置进度条增加的进度
  41. - (void)pathChanged:(NSTimer *)timer{
  42. self.strokeEnd += _plusWidth;
  43. if (self.strokeEnd > 0.60) {
  44. _plusWidth = 0.002;
  45. }
  46. if (self.strokeEnd > 0.85) {
  47. _plusWidth = 0.0007;
  48. }
  49. if (self.strokeEnd > 0.93) {
  50. _plusWidth = 0;
  51. }
  52. }
  53. //在KVO 计算 实际的读取进度时,调用改方法
  54. - (void)tg_WebViewPathChanged:(CGFloat)estimatedProgress {
  55. self.strokeEnd = estimatedProgress;
  56. }
  57. - (void)tg_startLoad {
  58. [_timer tg_webPageTimeWithTimeInterval:ProgressTimeInterval];
  59. }
  60. - (void)tg_finishedLoadWithError:(NSError *)error {
  61. CGFloat timer;
  62. if (error == nil) {
  63. [self tg_closeTimer];
  64. timer = 0.5;
  65. self.strokeEnd = 1.0;
  66. }else {
  67. timer = 45.0;
  68. }
  69. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timer * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  70. if (timer == 45.0) {
  71. [self tg_closeTimer];
  72. }
  73. self.hidden = YES;
  74. [self removeFromSuperlayer];
  75. });
  76. }
  77. #pragma mark - private
  78. - (void)tg_closeTimer {
  79. [_timer invalidate];
  80. _timer = nil;
  81. }
  82. - (void)dealloc {
  83. [self tg_closeTimer];
  84. }
  85. @end