Objective-C で Auto Layout を使いながらアプリ開発をしています。
ユーザの操作に反応してラベルの位置が変わるような仕組みを作りました。
画面をタップ・ドラッグすると、ラベルが指の位置に合わせて上下し、
指を離した時に、指を離した座標がラベルに設定されるというものです。
■ StoryBoard
![StoryBoard]WIDTH:600
■ アプリ起動時
![アプリ起動時]WIDTH:300
lang
1 2- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 3{ 4 CGPoint touch = [[touches anyObject] locationInView:self.view]; 5 label.center = CGPointMake(label.center.x, touch.y); 6} 7 8- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 9{ 10 CGPoint touch = [[touches anyObject] locationInView:self.view]; 11 label.center = CGPointMake(label.center.x, touch.y); 12} 13 14- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 15{ 16 CGPoint touch = [[touches anyObject] locationInView:self.view]; 17 label.text = [NSString stringWithFormat:@"y = %f", touch.y]; 18}
しかし、touchesEnded
イベント内で、
ラベルのテキストを変更しているのですが、
この時にラベルの座標が初期位置に戻ってしまいます。
■ 下へドラッグして…、
![下へドラッグして]WIDTH:300
■ 指を離すと何故か初期位置に戻る。
![指を離す]WIDTH:300
touchesEnded
を下記のように
ラベルを更新してから座標を設定するようにしても、
この現象は改善されませんでした。
lang
1- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 2{ 3 CGPoint touch = [[touches anyObject] locationInView:self.view]; 4 label.text = [NSString stringWithFormat:@"y = %f", touch.y]; 5 label.center = CGPointMake(label.center.x, touch.y); 6}
ラベル内のテキストを変更しないようにすると、
ラベルが勝手に初期位置に戻ったりしませんでした。
また、Auto Layout を使わないようにすることで、
テキストを変更しても位置がリセットされませんでしたが、
Auto Layout を使った上での解決法を知りたいです。
お分かりになる方が居らっしゃいましたら、
是非とも教えて頂けると助かります。
何卒よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。