1

1つのオブジェクトとユーザーが触れた場所の間に線を引こうとしています。サブクラス化を試しましたが、ユーザーが画面に触れるたびに「-(void)drawrect」を更新することができません。これらのファイルを削除して、コードを「-(void)touchesbegan」に正しく配置しようとしましたが、機能しません。

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    UITouch *touch = [touches anyObject];
    CGPoint locationOfTouch = [touch locationInView:nil];
    // You can now use locationOfTouch.x and locationOfTouch.y as the user's coordinates



Int xpos = (int)(starShip.center.x);
int ypos = (int)(starShip.center.y);

    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
       CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), starShip.center.x, starShip.center.y);
    //draws a line to the point where the user has touched the screen
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), locationOfTouch.x, locationOfTouch.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
}
4

1 に答える 1

0

drawRect:必要な場合にのみ呼び出されます。ビューが最初に表示されたとき、およびビューのサイズが変更されるたびに自動的に呼び出されます。タッチ後に呼び出されるようにする場合は、を呼び出す必要があります[self setNeedsDisplay];

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setNeedsDisplay];
}

これにより、drawRect:メソッドが確実に呼び出されます。drawRect:1つのフレームで複数回呼び出したため、直接呼び出すことはありません。ビューは複数回再描画されます。代わりに、を使用して再描画が必要であるというフラグを立てますsetNeedsDisplay。この方法drawRect:は、何度呼び出しても、一度だけ呼び出されますsetNeedsDisplay

于 2012-10-28T15:36:53.547 に答える