2013-04-16 4 views
0

이미지에 드래그 효과를 구현했지만 테스트 중에 클릭 마우스 이벤트에서만 이미지가 움직이는 것을 볼 수 있습니다.iOS : 드래그 효과가 잘 작동하지 않음

드래그 이벤트를 통해 내 이미지를 마우스로 움직일 수 없습니다. 그러나 화면의 한면을 클릭하면 이미지가 클릭 한 위치로 이동합니다.

나는 youtube에 많은 주제를 따라 갔지만 마침내 나는 같은 행동을하지 않았다.

이 내 코드 :

ScreenView1.h

IBOutlet UIImageView *image; 

ScreenView1.m 당신은 이미지보기를 드래그 할 경우, 사용 너무 훨씬 더 행복 할 것

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:touch.view]; 

    image.center = location; 
    [self ifCollision]; 
} 

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

답변

2

UIPanGestureRecognizer. 그것은 이런 일을 사소한 것으로 만듭니다. touchesBegan을 사용하는 것은 iOS 4입니다.

UIPanGestureRecognizer* p = 
    [[UIPanGestureRecognizer alloc] initWithTarget:self 
              action:@selector(dragging:)]; 
[imageView addGestureRecognizer:p]; 

// ... 

- (void) dragging: (UIPanGestureRecognizer*) p { 
    UIView* vv = p.view; 
    if (p.state == UIGestureRecognizerStateBegan || 
      p.state == UIGestureRecognizerStateChanged) { 
     CGPoint delta = [p translationInView: vv.superview]; 
     CGPoint c = vv.center; 
     c.x += delta.x; c.y += delta.y; 
     vv.center = c; 
     [p setTranslation: CGPointZero inView: vv.superview]; 
    } 
} 
+0

감사합니다. Matt. 그러나 저는 며칠이 지난이 환경에서 그렇게 발전하지 않았습니다. 좀 더 설명해 주시겠습니까? 내보기에 구성 요소 UIPanGestureRecognizer를 포함시켜야한다고 생각합니다. 맞춤 클래스를 연결했습니다. 하지만 그 후에는 코드를 어디에 넣을 수 있는지 정말로 알지 못합니다. –

+0

나는 당신을 도와 줄 전체 책을 썼다! 원하는 부분은 여기에서 시작합니다. http://www.aptt.com/iOSBook/ch18.html#_gesture_recognizers – matt

+0

Nice! 대단히 감사합니다 !!! –

0

당신은 드래그가 작동하지 않습니다 이유입니다는 touchesMoved:withEvent:에 옳은 일을하고 있지 않습니다. 여기에 작동하는 작은 코드는 다음과 같습니다 다른 사람을 위해

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInView:self]; 
    [CATransaction begin]; 
    [CATransaction setDisableActions:YES]; 
    [image setCenter:location]; 
    [CATransaction commit]; 
} 
+0

CATransaction에는 특정 포함이 필요합니까? 이 3 줄에서 오류가 있기 때문에 ... –

+0

또는 프레임 워크를 가져올 필요가 있습니까? –

+0

QuartzCore를 가져와야합니다. –

0

, 나는 그런 식으로 내 문제를 구현 한 :

- (IBAction)catchPanEvent:(UIPanGestureRecognizer *)recognizer{ 
    CGPoint translation = [recognizer translationInView:self.view]; 
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
             recognizer.view.center.y + translation.y); 

    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view]; 

} 

다시 매트 감사합니다!

관련 문제