You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

977 lines
43 KiB

1 month ago
  1. //
  2. // ChartViewController.m
  3. // HC
  4. //
  5. // Created by huilinLi on 2025/11/27.
  6. //
  7. #import "ChartViewController.h"
  8. #import "StockKLineModel.h"
  9. #import "StockInfoCardView.h"
  10. static CGFloat kLineUnitWidth = 5.0; // 单位宽度
  11. static CGFloat kPriceLabelAreaWidth = 35.0;
  12. static CGFloat kPriceLabelPadding = 10.0;
  13. static CGFloat kKLineHeight = 300.0;
  14. static CGFloat kContainerHeight = 120.0;
  15. @interface ChartViewController () <UIGestureRecognizerDelegate, UIScrollViewDelegate>
  16. @property (nonatomic, strong) StockInfoCardView *cardContainer;
  17. @property (nonatomic, strong) UIView *kSelectContainer;
  18. @property (nonatomic, strong) UIView *kLineContainer;
  19. @property (nonatomic, strong) UIView *macdContainer;
  20. @property (nonatomic, strong) UIView *kdjContainer;
  21. @property (nonatomic, strong) UIView *otherContainer;
  22. @property (nonatomic, strong) UIScrollView *kLineScrollView;
  23. @property (nonatomic, strong) NSArray *kLineData;
  24. @property (nonatomic, assign) NSInteger visibleKLineCount;
  25. @property (nonatomic, strong) NSArray<UILabel *> *priceLabels;
  26. @property (nonatomic, strong) UILabel *startDateLabel;
  27. @property (nonatomic, strong) UILabel *endDateLabel;
  28. @property (nonatomic, strong) UILabel *maLegendLabel; // MA5
  29. @property (nonatomic, strong) UILabel *macdLegendLabel; // DIF DEA
  30. @property (nonatomic, strong) UILabel *kdjLegendLabel; // K D
  31. @property (nonatomic, strong) UILabel *highPriceMarkLabel;
  32. @property (nonatomic, strong) UILabel *lowPriceMarkLabel;
  33. @property (nonatomic, assign) CGFloat currentMaxPrice;
  34. @property (nonatomic, assign) CGFloat currentMinPrice;
  35. @property (nonatomic, assign) CGFloat macdMaxValue;
  36. @property (nonatomic, assign) CGFloat macdMinValue;
  37. @property (nonatomic, assign) CGFloat kdjMaxValue;
  38. @property (nonatomic, assign) CGFloat kdjMinValue;
  39. // K线图层
  40. @property (nonatomic, strong) CAShapeLayer *redCandleLayer;
  41. @property (nonatomic, strong) CAShapeLayer *greenCandleLayer;
  42. // 均线图层
  43. @property (nonatomic, strong) CAShapeLayer *ma5Layer;
  44. @property (nonatomic, strong) CAShapeLayer *ma10Layer;
  45. @property (nonatomic, strong) CAShapeLayer *ma30Layer;
  46. // MACD图层
  47. @property (nonatomic, strong) CAShapeLayer *macdRedBarLayer;
  48. @property (nonatomic, strong) CAShapeLayer *macdGreenBarLayer;
  49. @property (nonatomic, strong) CAShapeLayer *difLayer;
  50. @property (nonatomic, strong) CAShapeLayer *deaLayer;
  51. @property (nonatomic, strong) CAShapeLayer *zeroLineLayer;
  52. // KDJ图层
  53. @property (nonatomic, strong) CAShapeLayer *kLayer;
  54. @property (nonatomic, strong) CAShapeLayer *dLayer;
  55. @property (nonatomic, strong) CAShapeLayer *jLayer;
  56. @property (nonatomic, strong) UIView *crossVerticalLine;
  57. @property (nonatomic, strong) UIView *crossHorizontalLine;
  58. @property (nonatomic, strong) UILabel *crossPriceLabel;
  59. @property (nonatomic, strong) UILabel *crossDateLabel;
  60. @property (nonatomic, assign) BOOL isLongPressing;
  61. @end
  62. @implementation ChartViewController
  63. #pragma mark - viewDidLoad
  64. - (void)viewDidLoad {
  65. [super viewDidLoad];
  66. self.view.backgroundColor = [UIColor blackColor];
  67. self.visibleKLineCount = 40;
  68. [self generateMockData];
  69. [self calculateMA];
  70. [self calculateMACD];
  71. [self calculateKDJ];
  72. [self setupSubviews];
  73. [self setupConstraints];
  74. [self setupDojiViews];
  75. CGFloat chartVisibleWidth = self.view.bounds.size.width - kPriceLabelAreaWidth;
  76. if (chartVisibleWidth > 0) {
  77. kLineUnitWidth = chartVisibleWidth / self.visibleKLineCount;
  78. }
  79. dispatch_async(dispatch_get_main_queue(), ^{
  80. CGFloat totalChartWidth = kLineUnitWidth * self.kLineData.count;
  81. self.kLineScrollView.contentSize = CGSizeMake(totalChartWidth, self.kLineContainer.bounds.size.height);
  82. // 滚到最右侧
  83. if (self.kLineScrollView.contentSize.width > self.kLineScrollView.bounds.size.width) {
  84. CGPoint offset = CGPointMake(self.kLineScrollView.contentSize.width - self.kLineScrollView.bounds.size.width, 0);//(横向偏移,纵向)
  85. [self.kLineScrollView setContentOffset:offset animated:NO];// 禁用动画效果
  86. }
  87. [self drawAllCharts];
  88. });
  89. }
  90. #pragma mark - 绘制
  91. - (void)drawAllCharts {
  92. if (self.kLineData.count == 0) return;
  93. // 获取当前ScrollView滚到了哪里
  94. CGFloat contentOffsetX = self.kLineScrollView.contentOffset.x;
  95. // 可视区域宽度
  96. CGFloat visibleWidth = self.kLineScrollView.bounds.size.width;
  97. NSInteger startIndex = floor(contentOffsetX / kLineUnitWidth);// 向下取整
  98. NSInteger endIndex = ceil((contentOffsetX + visibleWidth) / kLineUnitWidth);// 向上取整
  99. // 防止越界
  100. if (startIndex < 0) startIndex = 0;
  101. if (endIndex >= self.kLineData.count) endIndex = self.kLineData.count - 1;
  102. if (startIndex > endIndex) endIndex = startIndex;
  103. //start,end和偏移量传给所有子视图
  104. [self drawKLineChartFromIndex:startIndex toIndex:endIndex contentOffset:contentOffsetX];
  105. [self drawMACDChartFromIndex:startIndex toIndex:endIndex contentOffset:contentOffsetX];
  106. [self drawKDJChartFromIndex:startIndex toIndex:endIndex contentOffset:contentOffsetX];
  107. // 更新指标参数
  108. if (!self.isLongPressing) {
  109. NSInteger visibleEndIndex = endIndex;
  110. CGFloat visibleRightX = contentOffsetX + self.kLineScrollView.bounds.size.width;
  111. NSInteger calculatedIndex = floor(visibleRightX / kLineUnitWidth) - 1;
  112. if (calculatedIndex < 0) calculatedIndex = 0;
  113. if (calculatedIndex >= self.kLineData.count) calculatedIndex = self.kLineData.count - 1;
  114. visibleEndIndex = calculatedIndex;
  115. [self updateLegendsWithIndex:visibleEndIndex];
  116. }
  117. }
  118. - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  119. if (self.isLongPressing) {
  120. self.isLongPressing = NO;
  121. self.crossVerticalLine.hidden = YES;
  122. self.crossHorizontalLine.hidden = YES;
  123. self.crossPriceLabel.hidden = YES;
  124. self.crossDateLabel.hidden = YES;
  125. }
  126. [self drawAllCharts];
  127. }
  128. #pragma mark - 绘制K线+均线
  129. - (void)drawKLineChartFromIndex:(NSInteger)startIndex toIndex:(NSInteger)endIndex contentOffset:(CGFloat)contentOffsetX {
  130. // 图层大小=容器大小
  131. CGRect bounds = self.kLineContainer.bounds;
  132. self.redCandleLayer.frame = bounds;
  133. self.greenCandleLayer.frame = bounds;
  134. self.ma5Layer.frame = bounds;
  135. self.ma10Layer.frame = bounds;
  136. self.ma30Layer.frame = bounds;
  137. CGFloat chartHeight = bounds.size.height;
  138. // 最高最低价
  139. CGFloat maxPrice = 0, minPrice = 0;
  140. NSInteger maxIndex = -1, minIndex = -1;
  141. [self calculateMinMaxPriceForStartIndex:startIndex endIndex:endIndex maxPrice:&maxPrice minPrice:&minPrice maxIndex:&maxIndex minIndex:&minIndex];//将计算出的最高价赋值给max/minPrice
  142. self.currentMaxPrice = maxPrice;
  143. self.currentMinPrice = minPrice;
  144. CGFloat priceRange = maxPrice - minPrice;
  145. if (priceRange <= 0) {
  146. self.redCandleLayer.path = nil;
  147. return;
  148. }
  149. // 更新价格和日期
  150. [self updatePriceLabelsWithMaxPrice:maxPrice minPrice:minPrice];
  151. [self updateDateLabelsStartIndex:startIndex endIndex:endIndex];
  152. // 准备路径
  153. UIBezierPath *redPath = [UIBezierPath bezierPath];// 涨的路径
  154. UIBezierPath *greenPath = [UIBezierPath bezierPath];// 跌的路径
  155. UIBezierPath *ma5Path = [UIBezierPath bezierPath];// 均线路径
  156. UIBezierPath *ma10Path = [UIBezierPath bezierPath];
  157. UIBezierPath *ma30Path = [UIBezierPath bezierPath];
  158. CGFloat kLineWidth = kLineUnitWidth * 0.8;// k线实体宽度0.2是间隔
  159. BOOL f5 = YES, f10 = YES, f30 = YES;
  160. // 路径是否是第一个点(第一个点用moveToPoint,后面用addLineToPoint
  161. for (NSInteger i = startIndex; i <= endIndex; i++) {
  162. StockKLineModel *model = self.kLineData[i];
  163. // 坐标转换
  164. CGFloat xCenter = [self getScreenCenterXAtIndex:i contentOffset:contentOffsetX];
  165. CGFloat xLeft = xCenter - kLineWidth / 2.0;
  166. // 高度 * (最高价 - 当前价)/ 价格区间
  167. CGFloat yOpen = chartHeight * (maxPrice - model.open) / priceRange;
  168. CGFloat yClose = chartHeight * (maxPrice - model.close) / priceRange;
  169. CGFloat yHigh = chartHeight * (maxPrice - model.high) / priceRange;
  170. CGFloat yLow = chartHeight * (maxPrice - model.low) / priceRange;
  171. UIBezierPath *targetPath = (model.close >= model.open) ? redPath : greenPath;
  172. [targetPath moveToPoint:CGPointMake(xCenter, yHigh)];
  173. [targetPath addLineToPoint:CGPointMake(xCenter, yLow)];// 影线
  174. // 实体
  175. [targetPath appendPath:[UIBezierPath bezierPathWithRect:
  176. CGRectMake(xLeft,// 左边界
  177. MIN(yOpen, yClose),// 上边界
  178. kLineWidth,//
  179. MAX(1.0, fabs(yClose - yOpen)))]];//
  180. // 绘制均线
  181. void (^drawMA)(UIBezierPath*, CGFloat, BOOL*) = ^(UIBezierPath *p, CGFloat v, BOOL *f) {
  182. if (v > 0) {
  183. CGFloat y = chartHeight * (maxPrice - v) / priceRange;// y轴
  184. if (*f) {// 是第一个点
  185. [p moveToPoint:CGPointMake(xCenter, y)];// 移动到起点
  186. *f = NO; }// 起点已设置
  187. else { [p addLineToPoint:CGPointMake(xCenter, y)]; }// 连线,从上一个点链接这个点
  188. }
  189. };
  190. drawMA(ma5Path, model.MA5, &f5);
  191. drawMA(ma10Path, model.MA10, &f10);
  192. drawMA(ma30Path, model.MA30, &f30);
  193. }
  194. [CATransaction begin];// 开启Core Animation事务
  195. [CATransaction setDisableActions:YES];// 禁止动画
  196. self.redCandleLayer.path = redPath.CGPath;// 图层绑定
  197. self.greenCandleLayer.path = greenPath.CGPath;
  198. self.ma5Layer.path = ma5Path.CGPath;
  199. self.ma10Layer.path = ma10Path.CGPath;
  200. self.ma30Layer.path = ma30Path.CGPath;
  201. [CATransaction commit];// 事务提交
  202. // 更新最高最低价的箭头位置
  203. [self updateMaxMinArrowsWithMaxIndex:maxIndex minIndex:minIndex maxPrice:maxPrice minPrice:minPrice chartHeight:chartHeight range:priceRange contentOffsetX:contentOffsetX];
  204. }
  205. #pragma mark - 绘制MACD
  206. - (void)drawMACDChartFromIndex:(NSInteger)startIndex toIndex:(NSInteger)endIndex contentOffset:(CGFloat)contentOffsetX {
  207. CGRect bounds = self.macdContainer.bounds;
  208. self.macdRedBarLayer.frame = bounds;
  209. self.macdGreenBarLayer.frame = bounds;
  210. self.difLayer.frame = bounds;
  211. self.deaLayer.frame = bounds;
  212. self.zeroLineLayer.frame = bounds;
  213. CGFloat h = bounds.size.height;
  214. // 计算极值
  215. CGFloat maxV = -MAXFLOAT, minV = MAXFLOAT;// 先给正负无穷
  216. for (NSInteger i = startIndex; i <= endIndex; i++) {
  217. StockKLineModel *m = self.kLineData[i];
  218. maxV = MAX(maxV, MAX(m.macdBar, MAX(m.dif, m.dea)));
  219. minV = MIN(minV, MIN(m.macdBar, MIN(m.dif, m.dea)));
  220. }
  221. if (maxV == minV) { maxV += 1; minV -= 1; }
  222. self.macdMaxValue = maxV;
  223. self.macdMinValue = minV;
  224. CGFloat range = maxV - minV;
  225. CGFloat zeroY = h * (maxV - 0) / range;
  226. UIBezierPath *rPath = [UIBezierPath bezierPath];
  227. UIBezierPath *gPath = [UIBezierPath bezierPath];
  228. UIBezierPath *dPath = [UIBezierPath bezierPath];
  229. UIBezierPath *ePath = [UIBezierPath bezierPath];
  230. UIBezierPath *zPath = [UIBezierPath bezierPath];
  231. [zPath moveToPoint:CGPointMake(0, zeroY)];// 0轴起点
  232. [zPath addLineToPoint:CGPointMake(bounds.size.width, zeroY)];// 0轴终点
  233. CGFloat barWidth = kLineUnitWidth * 0.2;
  234. BOOL first = YES;// 快线慢线起点标记
  235. for (NSInteger i = startIndex; i <= endIndex; i++) {
  236. StockKLineModel *m = self.kLineData[i];
  237. CGFloat xCenter = [self getScreenCenterXAtIndex:i contentOffset:contentOffsetX];
  238. CGFloat xLeft = xCenter - barWidth/2.0;
  239. CGFloat yBar = h * (maxV - m.macdBar) / range;
  240. CGFloat barY = (m.macdBar > 0) ? yBar : zeroY;// 上边界
  241. CGFloat barH = MAX(0.5, fabs(zeroY - yBar));// 高度,大于0.5,省得看不见
  242. UIBezierPath *tp = (m.macdBar > 0) ? rPath : gPath;
  243. [tp appendPath:[UIBezierPath bezierPathWithRect:
  244. CGRectMake(xLeft,
  245. barY,
  246. barWidth,
  247. barH)]];
  248. CGFloat yD = h * (maxV - m.dif) / range;
  249. CGFloat yE = h * (maxV - m.dea) / range;
  250. if (first) {
  251. [dPath moveToPoint:CGPointMake(xCenter, yD)];
  252. [ePath moveToPoint:CGPointMake(xCenter, yE)];
  253. first = NO;
  254. } else {
  255. [dPath addLineToPoint:CGPointMake(xCenter, yD)];
  256. [ePath addLineToPoint:CGPointMake(xCenter, yE)];
  257. }
  258. }
  259. [CATransaction begin];
  260. [CATransaction setDisableActions:YES];
  261. self.macdRedBarLayer.path = rPath.CGPath;
  262. self.macdGreenBarLayer.path = gPath.CGPath;
  263. self.difLayer.path = dPath.CGPath;
  264. self.deaLayer.path = ePath.CGPath;
  265. self.zeroLineLayer.path = zPath.CGPath;
  266. [CATransaction commit];
  267. }
  268. #pragma mark - 绘制KDJ
  269. - (void)drawKDJChartFromIndex:(NSInteger)startIndex toIndex:(NSInteger)endIndex contentOffset:(CGFloat)contentOffsetX {
  270. self.kLayer.frame = self.kdjContainer.bounds;
  271. self.dLayer.frame = self.kdjContainer.bounds;
  272. self.jLayer.frame = self.kdjContainer.bounds;
  273. CGFloat h = self.kdjContainer.bounds.size.height;
  274. CGFloat maxV = 0, minV = 100;
  275. for (NSInteger i = startIndex; i <= endIndex; i++) {
  276. StockKLineModel *m = self.kLineData[i];
  277. maxV = MAX(maxV, MAX(m.K, MAX(m.D, m.J)));
  278. minV = MIN(minV, MIN(m.K, MIN(m.D, m.J)));
  279. }
  280. self.kdjMaxValue = maxV;
  281. self.kdjMinValue = minV;
  282. CGFloat range = maxV - minV;
  283. if (range <= 0) range = 1;
  284. UIBezierPath *kp = [UIBezierPath bezierPath];
  285. UIBezierPath *dp = [UIBezierPath bezierPath];
  286. UIBezierPath *jp = [UIBezierPath bezierPath];
  287. BOOL first = YES;
  288. for (NSInteger i = startIndex; i <= endIndex; i++) {
  289. StockKLineModel *m = self.kLineData[i];
  290. CGFloat xCenter = [self getScreenCenterXAtIndex:i contentOffset:contentOffsetX];
  291. CGFloat yK = h * (maxV - m.K) / range;
  292. CGFloat yD = h * (maxV - m.D) / range;
  293. CGFloat yJ = h * (maxV - m.J) / range;
  294. if (first) {
  295. [kp moveToPoint:CGPointMake(xCenter, yK)];
  296. [dp moveToPoint:CGPointMake(xCenter, yD)];
  297. [jp moveToPoint:CGPointMake(xCenter, yJ)];
  298. first = NO;
  299. } else {
  300. [kp addLineToPoint:CGPointMake(xCenter, yK)];
  301. [dp addLineToPoint:CGPointMake(xCenter, yD)];
  302. [jp addLineToPoint:CGPointMake(xCenter, yJ)];
  303. }
  304. }
  305. [CATransaction begin];
  306. [CATransaction setDisableActions:YES];
  307. self.kLayer.path = kp.CGPath;
  308. self.dLayer.path = dp.CGPath;
  309. self.jLayer.path = jp.CGPath;
  310. [CATransaction commit];
  311. }
  312. #pragma mark - 坐标计算
  313. // 获取某根K线在屏幕上的x轴中心坐标
  314. - (CGFloat)getScreenCenterXAtIndex:(NSInteger)index contentOffset:(CGFloat)offsetX {
  315. // 半个单位宽+索引*
  316. CGFloat x = kLineUnitWidth * (index + 0.5);
  317. // 屏幕坐标 = 绝对坐标 - 滚动偏移量 + 左侧空白区
  318. return x - offsetX + kPriceLabelAreaWidth;
  319. }
  320. #pragma mark - 极值箭头更新
  321. - (void)updateMaxMinArrowsWithMaxIndex:(NSInteger)maxIdx minIndex:(NSInteger)minIdx maxPrice:(CGFloat)maxPrice minPrice:(CGFloat)minPrice chartHeight:(CGFloat)height range:(CGFloat)range contentOffsetX:(CGFloat)offsetX {
  322. void (^updateLabel)(UILabel *, NSInteger, CGFloat) = ^(UILabel *label, NSInteger index, CGFloat price) {
  323. if (index >= 0 && index < self.kLineData.count) {
  324. label.hidden = NO;
  325. CGFloat xCenter = [self getScreenCenterXAtIndex:index contentOffset:offsetX];
  326. CGFloat y = height * (maxPrice - price) / range;// y轴位置
  327. // 默认放在k线右边
  328. label.text = [NSString stringWithFormat:@"← %.2f", price];
  329. [label sizeToFit];// 根据文字尺寸自适应标签长度
  330. CGFloat targetX = xCenter + kLineUnitWidth/2.0 + 2 + label.bounds.size.width/2.0;
  331. label.center = CGPointMake(targetX, y);
  332. // 如果label不在屏幕内,就放到k线左边
  333. if (CGRectGetMaxX(label.frame) > self.kLineContainer.bounds.size.width) {
  334. label.text = [NSString stringWithFormat:@"%.2f →", price];
  335. [label sizeToFit];
  336. targetX = xCenter - kLineUnitWidth/2.0 - 2 - label.bounds.size.width/2.0;
  337. label.center = CGPointMake(targetX, y);
  338. }
  339. } else {
  340. label.hidden = YES;
  341. }
  342. };
  343. StockKLineModel *maxModel = self.kLineData[maxIdx];
  344. updateLabel(self.highPriceMarkLabel, maxIdx, maxModel.high);
  345. StockKLineModel *minModel = self.kLineData[minIdx];
  346. updateLabel(self.lowPriceMarkLabel, minIdx, minModel.low);
  347. }
  348. #pragma mark - 更新指标数值
  349. - (void)updateLegendsWithIndex:(NSInteger)index {
  350. if (index < 0 || index >= self.kLineData.count) return;
  351. StockKLineModel *m = self.kLineData[index];
  352. NSMutableAttributedString * (^createStr)(NSString *, UIColor *) = ^(NSString *txt, UIColor *col) {
  353. return [[NSMutableAttributedString alloc] initWithString:txt attributes:@{NSForegroundColorAttributeName: col}];
  354. };
  355. // MA
  356. NSMutableAttributedString *maStr = [[NSMutableAttributedString alloc] init];
  357. [maStr appendAttributedString:createStr([NSString stringWithFormat:@"MA5:%.2f ", m.MA5], [UIColor yellowColor])];
  358. [maStr appendAttributedString:createStr([NSString stringWithFormat:@"MA10:%.2f ", m.MA10], [UIColor magentaColor])];
  359. [maStr appendAttributedString:createStr([NSString stringWithFormat:@"MA30:%.2f", m.MA30], [UIColor cyanColor])];
  360. self.maLegendLabel.attributedText = maStr;
  361. // MACD
  362. NSMutableAttributedString *macdStr = [[NSMutableAttributedString alloc] init];
  363. [macdStr appendAttributedString:createStr([NSString stringWithFormat:@"DIF:%.2f ", m.dif], [UIColor whiteColor])];
  364. [macdStr appendAttributedString:createStr([NSString stringWithFormat:@"DEA:%.2f ", m.dea], [UIColor yellowColor])];
  365. UIColor *barColor = (m.macdBar > 0) ? [UIColor redColor] : [UIColor greenColor];
  366. [macdStr appendAttributedString:createStr([NSString stringWithFormat:@"MACD:%.2f", m.macdBar], barColor)];
  367. self.macdLegendLabel.attributedText = macdStr;
  368. // KDJ
  369. NSMutableAttributedString *kdjStr = [[NSMutableAttributedString alloc] init];
  370. [kdjStr appendAttributedString:createStr([NSString stringWithFormat:@"K:%.2f ", m.K], [UIColor whiteColor])];
  371. [kdjStr appendAttributedString:createStr([NSString stringWithFormat:@"D:%.2f ", m.D], [UIColor yellowColor])];
  372. [kdjStr appendAttributedString:createStr([NSString stringWithFormat:@"J:%.2f", m.J], [UIColor magentaColor])];
  373. self.kdjLegendLabel.attributedText = kdjStr;
  374. }
  375. #pragma mark - 手势与缩放
  376. - (void)handlePinchGesture:(UIPinchGestureRecognizer *)gesture {
  377. if (self.isLongPressing) {// 缩放不显示十字星
  378. self.isLongPressing = NO;
  379. self.crossVerticalLine.hidden = YES;
  380. self.crossHorizontalLine.hidden = YES;
  381. self.crossPriceLabel.hidden = YES;
  382. self.crossDateLabel.hidden = YES;
  383. }
  384. if (gesture.state == UIGestureRecognizerStateChanged) {
  385. CGFloat scale = gesture.scale;
  386. CGFloat minUnitWidth = (self.view.bounds.size.width - kPriceLabelAreaWidth) / 500.0;
  387. CGFloat maxUnitWidth = 40.0;
  388. CGFloat newUnitWidth = MAX(minUnitWidth, MIN(kLineUnitWidth * scale, maxUnitWidth));
  389. // 屏幕中心点缩放
  390. CGFloat ratio = (self.kLineScrollView.contentOffset.x + self.kLineScrollView.bounds.size.width/2.0) / self.kLineScrollView.contentSize.width;
  391. kLineUnitWidth = newUnitWidth;// 全局更新
  392. // 新的滚动视图的内容宽度
  393. CGFloat newContentWidth = kLineUnitWidth * self.kLineData.count;
  394. self.kLineScrollView.contentSize = CGSizeMake(newContentWidth, self.kLineContainer.bounds.size.height);
  395. // 新的偏移量
  396. CGFloat newOffset = ratio * newContentWidth - self.kLineScrollView.bounds.size.width/2.0;
  397. self.kLineScrollView.contentOffset = CGPointMake(MAX(0, newOffset), 0);
  398. [self drawAllCharts];
  399. gesture.scale = 1.0;
  400. }
  401. }
  402. #pragma mark - 数据生成
  403. - (void)generateMockData {
  404. NSMutableArray *arr = [NSMutableArray array];
  405. CGFloat lastClose = 100.0;
  406. for (int i = 0; i < 2000; i++) {
  407. StockKLineModel *model = [[StockKLineModel alloc] init];
  408. NSDate *date = [NSDate dateWithTimeIntervalSinceNow:-(2000 - i) * 24 * 3600];
  409. NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
  410. [fmt setDateFormat:@"yyyy-MM-dd"];
  411. model.date = [fmt stringFromDate:date];
  412. CGFloat volatility = lastClose * 0.02;
  413. CGFloat randomChange = ((arc4random() % 100) / 100.0 - 0.5) * 2 * volatility;
  414. model.open = lastClose + ((arc4random() % 100) / 100.0 - 0.5) * volatility * 0.5;
  415. model.close = model.open + randomChange;
  416. CGFloat maxOC = MAX(model.open, model.close);
  417. CGFloat minOC = MIN(model.open, model.close);
  418. model.high = maxOC + (arc4random() % 100) / 100.0 * 1.0;
  419. model.low = minOC - (arc4random() % 100) / 100.0 * 1.0;
  420. if (model.low < 0) model.low = 0.01;
  421. [arr addObject:model];
  422. lastClose = model.close;
  423. }
  424. self.kLineData = arr;
  425. }
  426. - (void)calculateMA {
  427. for (int i = 0; i < self.kLineData.count; i++) {
  428. StockKLineModel *model = self.kLineData[i];
  429. model.MA5 = [self getMAWithIndex:i count:5];
  430. model.MA10 = [self getMAWithIndex:i count:10];
  431. model.MA30 = [self getMAWithIndex:i count:30];
  432. }
  433. }
  434. - (CGFloat)getMAWithIndex:(NSInteger)index count:(NSInteger)count {
  435. if (index < count - 1) return 0;
  436. CGFloat sum = 0;
  437. for (NSInteger i = index; i > index - count; i--) {
  438. StockKLineModel *m = self.kLineData[i];
  439. sum += m.close;
  440. }
  441. return sum / count;
  442. }
  443. - (void)calculateMACD {
  444. if (self.kLineData.count == 0) return;
  445. const CGFloat kShortEMA = 2.0 / (12 + 1);
  446. const CGFloat kLongEMA = 2.0 / (26 + 1);
  447. const CGFloat kSignalEMA = 2.0 / (9 + 1);
  448. CGFloat lastShortEMA = 0, lastLongEMA = 0, lastDEA = 0;
  449. for (int i = 0; i < self.kLineData.count; i++) {
  450. StockKLineModel *model = self.kLineData[i];
  451. CGFloat close = model.close;
  452. if (i == 0) {
  453. lastShortEMA = close; lastLongEMA = close;
  454. model.dif = 0; model.dea = 0; model.macdBar = 0;
  455. } else {
  456. lastShortEMA = kShortEMA * close + (1 - kShortEMA) * lastShortEMA;
  457. lastLongEMA = kLongEMA * close + (1 - kLongEMA) * lastLongEMA;
  458. model.dif = lastShortEMA - lastLongEMA;
  459. model.dea = kSignalEMA * model.dif + (1 - kSignalEMA) * lastDEA;
  460. model.macdBar = 2.0 * (model.dif - model.dea);
  461. }
  462. lastDEA = model.dea;
  463. }
  464. }
  465. - (void)calculateKDJ {
  466. CGFloat k = 50.0, d = 50.0;
  467. for (int i = 0; i < self.kLineData.count; i++) {
  468. StockKLineModel *model = self.kLineData[i];
  469. NSInteger startIndex = MAX(0, i - 8);
  470. CGFloat maxHigh = -MAXFLOAT;
  471. CGFloat minLow = MAXFLOAT;
  472. for (NSInteger j = startIndex; j <= i; j++) {
  473. StockKLineModel *m = self.kLineData[j];
  474. maxHigh = MAX(maxHigh, m.high);
  475. minLow = MIN(minLow, m.low);
  476. }
  477. CGFloat rsv = 0;
  478. if (maxHigh != minLow) rsv = (model.close - minLow) / (maxHigh - minLow) * 100.0;
  479. k = (2.0 * k + rsv) / 3.0;
  480. d = (2.0 * d + k) / 3.0;
  481. model.K = k; model.D = d; model.J = 3.0 * k - 2.0 * d;
  482. }
  483. }
  484. #pragma mark 计算极值
  485. - (void)calculateMinMaxPriceForStartIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex maxPrice:(CGFloat *)maxPrice minPrice:(CGFloat *)minPrice maxIndex:(NSInteger *)maxIdx minIndex:(NSInteger *)minIdx {
  486. *maxPrice = -MAXFLOAT; *minPrice = MAXFLOAT;
  487. *maxIdx = -1; *minIdx = -1;
  488. if (self.kLineData.count == 0) return;
  489. for (NSInteger i = startIndex; i <= endIndex; i++) {
  490. StockKLineModel *m = self.kLineData[i];
  491. if (m.high > *maxPrice) { *maxPrice = m.high; *maxIdx = i; }
  492. if (m.low < *minPrice) { *minPrice = m.low; *minIdx = i; }
  493. if (m.MA5 > 0) { *maxPrice = MAX(*maxPrice, m.MA5); *minPrice = MIN(*minPrice, m.MA5); }
  494. if (m.MA10 > 0) { *maxPrice = MAX(*maxPrice, m.MA10); *minPrice = MIN(*minPrice, m.MA10); }
  495. if (m.MA30 > 0) { *maxPrice = MAX(*maxPrice, m.MA30); *minPrice = MIN(*minPrice, m.MA30); }
  496. }
  497. if (*maxPrice > *minPrice) {
  498. CGFloat d = *maxPrice - *minPrice;
  499. *maxPrice += d * 0.05; *minPrice -= d * 0.05;
  500. }
  501. }
  502. #pragma mark - setupSubviews
  503. -(void) setupSubviews {
  504. UIColor *bgColor = [UIColor colorWithRed:26.0/255.0 green:26.0/255.0 blue:26.0/255.0 alpha:1.0];
  505. _cardContainer = [[StockInfoCardView alloc] init];
  506. _cardContainer.translatesAutoresizingMaskIntoConstraints = NO;
  507. [_cardContainer setupView];
  508. [self.view addSubview:_cardContainer];
  509. _kSelectContainer = [[UIView alloc] init];
  510. _kSelectContainer.backgroundColor = bgColor;
  511. _kSelectContainer.translatesAutoresizingMaskIntoConstraints = NO;
  512. [self.view addSubview:_kSelectContainer];
  513. [self addKSelectOptions];
  514. self.kLineContainer = [self createContainerViewWithColor:bgColor];
  515. self.macdContainer = [self createContainerViewWithColor:bgColor];
  516. self.kdjContainer = [self createContainerViewWithColor:bgColor];
  517. self.otherContainer = [self createContainerViewWithColor:bgColor];
  518. self.kLineScrollView = [[UIScrollView alloc] init];
  519. self.kLineScrollView.backgroundColor = [UIColor clearColor];
  520. self.kLineScrollView.showsHorizontalScrollIndicator = NO;
  521. self.kLineScrollView.translatesAutoresizingMaskIntoConstraints = NO;
  522. self.kLineScrollView.delegate = self;
  523. [self.kLineContainer addSubview:self.kLineScrollView];
  524. [NSLayoutConstraint activateConstraints:@[
  525. [self.kLineScrollView.topAnchor constraintEqualToAnchor:self.kLineContainer.topAnchor],
  526. [self.kLineScrollView.bottomAnchor constraintEqualToAnchor:self.kLineContainer.bottomAnchor],
  527. [self.kLineScrollView.leadingAnchor constraintEqualToAnchor:self.kLineContainer.leadingAnchor constant:kPriceLabelAreaWidth],
  528. [self.kLineScrollView.trailingAnchor constraintEqualToAnchor:self.kLineContainer.trailingAnchor],
  529. ]];
  530. UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  531. [self.kLineScrollView addGestureRecognizer:pinchGesture];
  532. [self setupAllLayers];
  533. [self setupLabels];
  534. self.maLegendLabel = [self createLegendLabel];
  535. [self.view addSubview:self.maLegendLabel];
  536. self.macdLegendLabel = [self createLegendLabel];
  537. [self.view addSubview:self.macdLegendLabel];
  538. self.kdjLegendLabel = [self createLegendLabel];
  539. [self.view addSubview:self.kdjLegendLabel];
  540. [NSLayoutConstraint activateConstraints:@[
  541. [self.maLegendLabel.leadingAnchor constraintEqualToAnchor:self.kLineContainer.leadingAnchor constant:kPriceLabelAreaWidth],
  542. [self.maLegendLabel.bottomAnchor constraintEqualToAnchor:self.kLineContainer.topAnchor],
  543. [self.macdLegendLabel.leadingAnchor constraintEqualToAnchor:self.macdContainer.leadingAnchor constant:kPriceLabelAreaWidth],
  544. [self.macdLegendLabel.bottomAnchor constraintEqualToAnchor:self.macdContainer.topAnchor],
  545. [self.kdjLegendLabel.leadingAnchor constraintEqualToAnchor:self.kdjContainer.leadingAnchor constant:kPriceLabelAreaWidth],
  546. [self.kdjLegendLabel.bottomAnchor constraintEqualToAnchor:self.kdjContainer.topAnchor]
  547. ]];
  548. self.highPriceMarkLabel = [self createMarkLabel];
  549. [self.kLineContainer addSubview:self.highPriceMarkLabel];
  550. self.lowPriceMarkLabel = [self createMarkLabel];
  551. [self.kLineContainer addSubview:self.lowPriceMarkLabel];
  552. }
  553. - (UIView *)createContainerViewWithColor:(UIColor *)color {
  554. UIView *uiView = [[UIView alloc] init];
  555. uiView.backgroundColor = color;
  556. uiView.translatesAutoresizingMaskIntoConstraints = NO;
  557. uiView.clipsToBounds = YES;
  558. [self.view addSubview:uiView];
  559. return uiView;
  560. }
  561. #pragma mark - setupConstraints
  562. - (void)setupConstraints {
  563. [NSLayoutConstraint activateConstraints:@[
  564. [_cardContainer.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
  565. [_cardContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
  566. [_cardContainer.widthAnchor constraintEqualToAnchor:self.view.widthAnchor],
  567. [_cardContainer.heightAnchor constraintEqualToConstant:100],
  568. [_kSelectContainer.topAnchor constraintEqualToAnchor:_cardContainer.bottomAnchor constant:5],
  569. [_kSelectContainer.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
  570. [_kSelectContainer.widthAnchor constraintEqualToAnchor:self.view.widthAnchor],
  571. [_kSelectContainer.heightAnchor constraintEqualToConstant:40],
  572. ]];
  573. // 循环设置图表容器约束
  574. NSArray *containers = @[self.kLineContainer, self.macdContainer, self.kdjContainer, self.otherContainer];
  575. NSArray *heights = @[@(kKLineHeight), @(kContainerHeight), @(kContainerHeight), @(kContainerHeight)];
  576. UIView *previousView = _kSelectContainer;
  577. for (int i = 0; i < containers.count; i++) {
  578. UIView *container = containers[i];
  579. // 间距 第一个是15MACD是30,其他是15
  580. CGFloat spacing = (i == 1) ? 30.0 : 15.0;
  581. [NSLayoutConstraint activateConstraints:@[
  582. [container.topAnchor constraintEqualToAnchor:previousView.bottomAnchor constant:spacing],
  583. [container.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
  584. [container.widthAnchor constraintEqualToAnchor:self.view.widthAnchor],
  585. [container.heightAnchor constraintEqualToConstant:[heights[i] floatValue]]
  586. ]];
  587. previousView = container;
  588. }
  589. }
  590. - (void)setupAllLayers {
  591. // K线
  592. _redCandleLayer = [self createLayerColor:[UIColor redColor] width:1.0 filled:YES];
  593. _greenCandleLayer = [self createLayerColor:[UIColor greenColor] width:1.0 filled:YES];
  594. [self.kLineContainer.layer insertSublayer:_redCandleLayer atIndex:0];
  595. [self.kLineContainer.layer insertSublayer:_greenCandleLayer atIndex:0];
  596. // 均线
  597. _ma5Layer = [self createLayerColor:[UIColor yellowColor] width:1.0 filled:NO];
  598. _ma10Layer = [self createLayerColor:[UIColor magentaColor] width:1.0 filled:NO];
  599. _ma30Layer = [self createLayerColor:[UIColor cyanColor] width:1.0 filled:NO];
  600. [self.kLineContainer.layer insertSublayer:_ma5Layer below:_redCandleLayer];
  601. [self.kLineContainer.layer insertSublayer:_ma10Layer below:_ma5Layer];
  602. [self.kLineContainer.layer insertSublayer:_ma30Layer below:_ma10Layer];
  603. // MACD
  604. _macdRedBarLayer = [self createLayerColor:[UIColor redColor] width:0 filled:YES];
  605. _macdGreenBarLayer = [self createLayerColor:[UIColor greenColor] width:0 filled:YES];
  606. _difLayer = [self createLayerColor:[UIColor whiteColor] width:1.0 filled:NO];
  607. _deaLayer = [self createLayerColor:[UIColor yellowColor] width:1.0 filled:NO];
  608. _zeroLineLayer = [self createLayerColor:[UIColor grayColor] width:0.5 filled:NO];
  609. [self.macdContainer.layer insertSublayer:_zeroLineLayer atIndex:0];
  610. [self.macdContainer.layer insertSublayer:_macdRedBarLayer above:_zeroLineLayer];
  611. [self.macdContainer.layer insertSublayer:_macdGreenBarLayer above:_macdRedBarLayer];
  612. [self.macdContainer.layer insertSublayer:_difLayer above:_macdGreenBarLayer];
  613. [self.macdContainer.layer insertSublayer:_deaLayer above:_difLayer];
  614. // KDJ
  615. _kLayer = [self createLayerColor:[UIColor whiteColor] width:1.0 filled:NO];
  616. _dLayer = [self createLayerColor:[UIColor yellowColor] width:1.0 filled:NO];
  617. _jLayer = [self createLayerColor:[UIColor magentaColor] width:1.0 filled:NO];
  618. [self.kdjContainer.layer insertSublayer:_kLayer atIndex:0];
  619. [self.kdjContainer.layer insertSublayer:_dLayer above:_kLayer];
  620. [self.kdjContainer.layer insertSublayer:_jLayer above:_dLayer];
  621. }
  622. - (CAShapeLayer *)createLayerColor:(UIColor *)color width:(CGFloat)width filled:(BOOL)fill {
  623. CAShapeLayer *layer = [CAShapeLayer layer];
  624. layer.lineWidth = width;
  625. layer.strokeColor = color.CGColor;
  626. layer.fillColor = fill ? color.CGColor : [UIColor clearColor].CGColor;
  627. layer.lineCap = kCALineCapSquare;
  628. layer.lineJoin = kCALineJoinRound;// 圆角连接,避免折线拐角出现尖锐锯齿
  629. return layer;
  630. }
  631. - (UILabel *)createLegendLabel {
  632. UILabel *label = [[UILabel alloc] init];
  633. label.font = [UIFont systemFontOfSize:10];
  634. label.textColor = [UIColor whiteColor];
  635. label.backgroundColor = [UIColor clearColor];
  636. label.translatesAutoresizingMaskIntoConstraints = NO;
  637. return label;
  638. }
  639. - (UILabel *)createMarkLabel {
  640. UILabel *label = [[UILabel alloc] init];
  641. label.font = [UIFont systemFontOfSize:10];
  642. label.textColor = [UIColor whiteColor];
  643. label.backgroundColor = [UIColor clearColor];
  644. label.hidden = YES;
  645. return label;
  646. }
  647. - (void)setupLabels {
  648. NSMutableArray *priceLabelArr = [NSMutableArray array];
  649. CGFloat chartUsableHeight = kKLineHeight - kPriceLabelPadding;
  650. for (NSInteger i = 0; i < 5; i++) {
  651. UILabel *label = [[UILabel alloc] init];
  652. label.text = @"--";
  653. label.textColor = [UIColor lightGrayColor];
  654. label.font = [UIFont systemFontOfSize:10];
  655. label.translatesAutoresizingMaskIntoConstraints = NO;
  656. [self.kLineContainer addSubview:label];
  657. [NSLayoutConstraint activateConstraints:@[
  658. [label.leadingAnchor constraintEqualToAnchor:self.kLineContainer.leadingAnchor constant:2],
  659. [label.topAnchor constraintEqualToAnchor:self.kLineContainer.topAnchor constant: (chartUsableHeight / 4 * i)]
  660. ]];
  661. [priceLabelArr addObject:label];
  662. }
  663. self.priceLabels = priceLabelArr;
  664. self.startDateLabel = [[UILabel alloc] init];
  665. self.startDateLabel.textColor = [UIColor lightGrayColor];
  666. self.startDateLabel.font = [UIFont systemFontOfSize:10];
  667. self.startDateLabel.translatesAutoresizingMaskIntoConstraints = NO;
  668. [self.view addSubview:self.startDateLabel];
  669. self.endDateLabel = [[UILabel alloc] init];
  670. self.endDateLabel.textColor = [UIColor lightGrayColor];
  671. self.endDateLabel.font = [UIFont systemFontOfSize:10];
  672. self.endDateLabel.textAlignment = NSTextAlignmentRight;
  673. self.endDateLabel.translatesAutoresizingMaskIntoConstraints = NO;
  674. [self.view addSubview:self.endDateLabel];
  675. [NSLayoutConstraint activateConstraints:@[
  676. [self.startDateLabel.leadingAnchor constraintEqualToAnchor:self.kLineContainer.leadingAnchor constant:kPriceLabelAreaWidth],
  677. [self.startDateLabel.topAnchor constraintEqualToAnchor:self.kLineContainer.bottomAnchor constant:2],
  678. [self.endDateLabel.trailingAnchor constraintEqualToAnchor:self.kLineContainer.trailingAnchor],
  679. [self.endDateLabel.topAnchor constraintEqualToAnchor:self.kLineContainer.bottomAnchor constant:2],
  680. ]];
  681. }
  682. #pragma mark - 左侧价格刻度计算
  683. - (void)updatePriceLabelsWithMaxPrice:(CGFloat)maxPrice minPrice:(CGFloat)minPrice {
  684. CGFloat range = maxPrice - minPrice;
  685. for (NSInteger i = 0; i < 5; i++) {
  686. self.priceLabels[i].text = [NSString stringWithFormat:@"%.2f", maxPrice - range / 4.0 * i];
  687. }
  688. }
  689. # pragma mark - 日期计算
  690. - (void)updateDateLabelsStartIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex {
  691. if (self.kLineData.count > 0) {
  692. if (startIndex < self.kLineData.count) self.startDateLabel.text = ((StockKLineModel *)self.kLineData[startIndex]).date;
  693. if (endIndex < self.kLineData.count) self.endDateLabel.text = ((StockKLineModel *)self.kLineData[endIndex]).date;
  694. }
  695. }
  696. #pragma mark - k线选择
  697. - (void)addKSelectOptions {
  698. NSArray *titles = @[@"分时",@"日k", @"周k", @"月k", @"更多", @"设置"];
  699. UIStackView *stackView = [[UIStackView alloc] init];
  700. stackView.axis = UILayoutConstraintAxisHorizontal;
  701. stackView.distribution = UIStackViewDistributionFillEqually;
  702. stackView.alignment = UIStackViewAlignmentCenter;
  703. stackView.spacing = 5.0;
  704. stackView.translatesAutoresizingMaskIntoConstraints = NO;
  705. for (NSString *title in titles) {
  706. UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
  707. [button setTitle:title forState:UIControlStateNormal];
  708. button.titleLabel.font = [UIFont systemFontOfSize:14];
  709. [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  710. [stackView addArrangedSubview:button];
  711. }
  712. [_kSelectContainer addSubview:stackView];
  713. [NSLayoutConstraint activateConstraints:@[
  714. [stackView.leadingAnchor constraintEqualToAnchor:_kSelectContainer.leadingAnchor constant:10],
  715. [stackView.trailingAnchor constraintEqualToAnchor:_kSelectContainer.trailingAnchor constant:-10],
  716. [stackView.topAnchor constraintEqualToAnchor:_kSelectContainer.topAnchor constant:15],
  717. [stackView.bottomAnchor constraintEqualToAnchor:_kSelectContainer.bottomAnchor constant:-15]
  718. ]];
  719. }
  720. #pragma mark - 十字星
  721. - (void)setupDojiViews {
  722. // 竖线
  723. self.crossVerticalLine = [[UIView alloc] init];
  724. self.crossVerticalLine.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
  725. self.crossVerticalLine.hidden = YES;
  726. self.crossVerticalLine.userInteractionEnabled = NO; // 不挡手势
  727. [self.view addSubview:self.crossVerticalLine];
  728. // 横线
  729. self.crossHorizontalLine = [[UIView alloc] init];
  730. self.crossHorizontalLine.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
  731. self.crossHorizontalLine.hidden = YES;
  732. self.crossHorizontalLine.userInteractionEnabled = NO;
  733. [self.view addSubview:self.crossHorizontalLine];
  734. // 价格
  735. self.crossPriceLabel = [[UILabel alloc] init];
  736. self.crossPriceLabel.backgroundColor = [UIColor systemBlueColor];
  737. self.crossPriceLabel.textColor = [UIColor whiteColor];
  738. self.crossPriceLabel.font = [UIFont systemFontOfSize:9];
  739. self.crossPriceLabel.textAlignment = NSTextAlignmentCenter;
  740. self.crossPriceLabel.clipsToBounds = YES;
  741. self.crossPriceLabel.layer.cornerRadius = 2.0;
  742. self.crossPriceLabel.hidden = YES;
  743. [self.view addSubview:self.crossPriceLabel];
  744. // 日期
  745. self.crossDateLabel = [[UILabel alloc] init];
  746. self.crossDateLabel.backgroundColor = [UIColor systemBlueColor];
  747. self.crossDateLabel.textColor = [UIColor whiteColor];
  748. self.crossDateLabel.font = [UIFont systemFontOfSize:9];
  749. self.crossDateLabel.textAlignment = NSTextAlignmentCenter;// 居中对齐
  750. //NSTextAlignmentJustified 两端对齐
  751. self.crossDateLabel.clipsToBounds = YES;
  752. self.crossDateLabel.layer.cornerRadius = 2.0;
  753. self.crossDateLabel.hidden = YES;
  754. [self.view addSubview:self.crossDateLabel];
  755. NSArray *targetViews = @[self.kLineScrollView, self.macdContainer, self.kdjContainer];
  756. for (UIView *view in targetViews) {
  757. // 必须在循环里创建新的手势对象,因为一个手势只能绑定一个View
  758. UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
  759. longPress.minimumPressDuration = 0.3; // 设置触发时间
  760. [view addGestureRecognizer:longPress];
  761. }
  762. }
  763. - (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
  764. CGPoint touchPoint = [gesture locationInView:self.kLineScrollView];
  765. CGPoint touchPointInView = [gesture locationInView:self.view];
  766. CGFloat offsetX = self.kLineScrollView.contentOffset.x;
  767. NSInteger index = floor(touchPoint.x / kLineUnitWidth);// 向下取整
  768. if (index < 0) index = 0;
  769. if (index >= self.kLineData.count) index = self.kLineData.count - 1;
  770. if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {// 手势开始/移动
  771. self.isLongPressing = YES;
  772. self.crossVerticalLine.hidden = NO;
  773. self.crossHorizontalLine.hidden = NO;
  774. self.crossPriceLabel.hidden = NO;
  775. self.crossDateLabel.hidden = NO;// 显示十字星
  776. // 更新竖线位置
  777. CGFloat xCenterInScroll = kLineUnitWidth * 0.5 + kLineUnitWidth * index;
  778. //滚动视图x坐标 - 滚动偏移量 + 价格标签宽度
  779. CGFloat xCenterInView = xCenterInScroll - offsetX + kPriceLabelAreaWidth;
  780. // 不要越界
  781. if (xCenterInView < kPriceLabelAreaWidth || xCenterInView > self.view.bounds.size.width) return;
  782. CGFloat topY = self.kLineContainer.frame.origin.y;// k线容器在主视图的顶部y
  783. CGFloat bottomY = CGRectGetMaxY(self.otherContainer.frame);// 空容器的底部
  784. self.crossVerticalLine.frame = CGRectMake(xCenterInView, topY, 0.5, bottomY - topY);
  785. CGFloat displayValue = 0.0;
  786. BOOL isTouchValid = NO; // 用于标记是否摸到了有效的图表区域
  787. // 判断手指在哪个容器里
  788. if (CGRectContainsPoint(self.kLineContainer.frame, touchPointInView)) {// CGRectContainsPoint(矩形区域,) 布尔:
  789. isTouchValid = YES;
  790. CGFloat relativeY = touchPointInView.y - self.kLineContainer.frame.origin.y;
  791. CGFloat height = self.kLineContainer.frame.size.height;
  792. displayValue = self.currentMaxPrice - (relativeY / height) * (self.currentMaxPrice - self.currentMinPrice);
  793. } else if (CGRectContainsPoint(self.macdContainer.frame, touchPointInView)) {
  794. isTouchValid = YES;
  795. CGFloat relativeY = touchPointInView.y - self.macdContainer.frame.origin.y;
  796. CGFloat height = self.macdContainer.frame.size.height;
  797. displayValue = self.macdMaxValue - (relativeY / height) * (self.macdMaxValue - self.macdMinValue);
  798. } else if (CGRectContainsPoint(self.kdjContainer.frame, touchPointInView)) {
  799. isTouchValid = YES;
  800. CGFloat relativeY = touchPointInView.y - self.kdjContainer.frame.origin.y;
  801. CGFloat height = self.kdjContainer.frame.size.height;
  802. displayValue = self.kdjMaxValue - (relativeY / height) * (self.kdjMaxValue - self.kdjMinValue);
  803. }
  804. // 只有触摸在图表内才更新横线
  805. if (isTouchValid) {
  806. self.crossHorizontalLine.frame = CGRectMake(kPriceLabelAreaWidth, touchPointInView.y, self.view.bounds.size.width - kPriceLabelAreaWidth, 0.5);
  807. self.crossPriceLabel.text = [NSString stringWithFormat:@" %.2f ", displayValue];
  808. [self.crossPriceLabel sizeToFit];
  809. self.crossPriceLabel.center = CGPointMake(kPriceLabelAreaWidth / 2.0, touchPointInView.y);
  810. }
  811. StockKLineModel *model = self.kLineData[index];
  812. self.crossDateLabel.text = [NSString stringWithFormat:@" %@ ", model.date];
  813. [self.crossDateLabel sizeToFit];
  814. CGFloat dateLabelY = CGRectGetMaxY(self.kLineContainer.frame);
  815. self.crossDateLabel.center = CGPointMake(xCenterInView, dateLabelY);
  816. [self updateLegendsWithIndex:index];
  817. } else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled) {// 结束/取消
  818. self.isLongPressing = NO;
  819. self.crossVerticalLine.hidden = YES;
  820. self.crossHorizontalLine.hidden = YES;
  821. self.crossPriceLabel.hidden = YES;
  822. self.crossDateLabel.hidden = YES;
  823. [self drawAllCharts];
  824. }
  825. }
  826. @end