背景:ユーザーがどこかをタッチアップしたときにブロックを描画したいと思います。ブロックがあれば消したいです。NSMutableArray
ブロックがどこに行くべきかを追跡するためにを使用してブロックを管理します。ユーザーがタッチするたびに、タッチ場所にすでにブロックが含まれているかどうかが判断され、それに応じて配列が管理されます。
問題:これから非常に奇妙なフィードバックがありました。まず第一に、配列内のすべてが私が望むように機能します。問題は、ユーザーがブロックを消去したいときに発生します。配列は正しく維持されていますが、図面は配列の変更を無視しているようです。最後のドット以外は削除されません。そして、それでも、ユーザーが他の場所をクリックすると、点滅がオンとオフに切り替わります。
コードは次のとおりです。
- (void)drawRect:(CGRect)rect
{
NSLog(@"drawrect current array %@",pointArray);
for (NSValue *pointValue in pointArray){
CGPoint point = [pointValue CGPointValue];
[self drawSquareAt:point];
}
}
- (void) drawSquareAt:(CGPoint) point{
float x = point.x * scale;
float y = point.y * scale;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x+scale, y);
CGContextAddLineToPoint(context, x+scale, y+scale);
CGContextAddLineToPoint(context, x, y+scale);
CGContextAddLineToPoint(context, x, y);
CGContextSetFillColorWithColor(context, [UIColor darkGrayColor].CGColor);
CGContextFillPath(context);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *aTouch = [touches anyObject];
CGPoint point = [aTouch locationInView:self];
point = CGPointMake( (int) (point.x/scale), (int) (point.y/scale));
NSLog(@"Touched at %@", [NSArray arrayWithObject: [NSValue valueWithCGPoint:point]]);
NSValue *pointValue = [NSValue valueWithCGPoint:point];
int i = [pointArray indexOfObject:pointValue];
NSLog(@"Index at %i",i);
if (i < [pointArray count]){
[pointArray removeObjectAtIndex:i];
NSLog(@"remove");
}else {
[pointArray addObject:pointValue];
NSLog(@"add");
}
NSLog(@"Current array : %@", pointArray);
[self setNeedsDisplay];
}
scale
は16として定義され
pointArray
ます。はビューのメンバー変数です。
テストするには:これを任意のUIViewにドロップし、それをviewControllerに追加して、効果を確認できます。
質問:図面を配列と一致させるにはどうすればよいですか?
更新+説明:私はこのアプローチのコストを認識していますが、それは私が簡単に把握するためにのみ作成されています。実際のアプリケーションでは使用されませんので、高価なことにこだわらないでください。この機能を作成したのは、描画した図形のNSString
( )の値を取得するためだけです。@"1,3,5,1,2,6,2,5,5,..."
これは、実際に再描画せずに使用すると、より効率的になります。尋ねられた質問に固執してください。ありがとうございました。