我认为这实际上只是一个实现细节,所以这取决于您如何。我猜他们在 -drawRect 中做了所有事情,但是,如果你愿意,你可以使用 Core Animation 层来实现它。
如果您已经使用 -drawRect 绘制图形,那么坚持使用它是有意义的,但是,如果您只想为黄点和垂直黄线叠加图层您可以只使用常规 CALayer 并更改它们的位置以响应 -touchesMoved。
// Create a line layer with a 1px width and yellow bg
CALayer *lineLayer = [CALayer layer];
[lineLayer setBounds:CGRectMake(0.0f, 0.0f, 1.0f, parentViewHeight)];
[lineLayer setPosition:CGPointMake(currentX, parentViewHeight/2.0f)];
[lineLayer setBackgroundColor:[[UIColor yellowColor] CGColor]];
[[parentView layer] addSublayer:lineLayer];
// Create a dot layer with the contents set to a CGImageRef
UIImage *dotImage = [UIImage imageNamed:@"yellowdot.png"];
CALayer *dotLayer = [CALayer layer];
[dotLayer setBounds:CGRectMake(0.0f, 0.0f, [dotImage size].width,
[dotImage size].height)];
[dotLayer setPosition:[lineLayer position]];
[dotLayer setContents:[dotImage CGImage]];
[[parentView layer] addSublayer:dotLayer];
您需要使这些层成为您的类的 ivars,以便当您收到触摸事件时,您可以更新它们的位置。
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
{
CGPoint current = [[touches anyObject] locationInView:parentView];
[lineLayer setPosition:CGPointMake(current.x, [lineLayer position].y)];
[dotLayer setPosition:CGPointMake(current.x, [self yForStockPriceAtPoint:current])];
[super touchesMoved:touches withEvent:event];
}