ビューを指で動かす
ビューを指で動かす
今回はUIPanGestureRecognizerでビューをタッチしたまま
任意の所へ移動するやり方を書きます。
・UIPanGestureRecognizer
スタンプなどでよく使われる機能だと思います。
ではタッチイベントの生成を書きます。
例文
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(PanGesture:)];
[_viewObject addGestureRecognizer:panGestureRecognizer];
これで生成されるイベントを任意の場所に配置して
呼び出されるセレクターを書きます。
-(void)PanGesture:(UIPanGestureRecognizer *)sender
{
//ドラッグ時の処理
UIView *targetView = sender.view;
CGPoint p = [sender translationInView:targetView];
CGPoint movedPoint = CGPointMake(targetView.center.x + p.x, targetView.center.y + p.y);
targetView.center = movedPoint;
[sender setTranslation:CGPointZeroinView:targetView];
}
これで指でビューを移動できるようになると思います。
・タッチイベントで気をつける事
開発中あった事ですがコードもエラーも無いのに全くタッチ反応が無い。
そんな時に疑うのはビュー自体のタッチイベントです。
デフォルトのビューのタッチイベントではタッチイベントを検知しないのです。
そこにイベントを許可されるコードを書きましょう。
[viewObject setUserInteractionEnabled:YES];
これでタッチイベントが検出されます。
逆にタッチイベントを検出したくない時はNOにしましょう。