2012-08-12 7 views
1

제스처 인식기를 제 단추에 추가하여 사용자가 단추 프레임을 스 와이프 한 경우 코드를 실행할 수 있습니다. 스 와이프가 위로, 오른쪽, 왼쪽 또는 아래쪽으로 있으면이 코드가 달라지기를 바랍니다.UIGestureRecognizer를 어떻게 초기화합니까?

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    button.frame=CGRectMake(0, 0, 100, 100); 
    [self.view addSubview:button]; 
    UIGestureRecognizer *swipe=[[UIGestureRecognizer alloc]initWithTarget:button action:@selector(detectSwipe)]; 
    [button addGestureRecognizer:swipe]; 
} 

그래서 initWithTarget:action: 일이 올바 릅니까? 이제 어떻게할까요? detectSwipe 메서드를 구현하는 방법은 무엇입니까?

다음은 제스처 인식기의 대상을 제외한 모든 권리를 가지고 detectSwipe

  -(IBAction)detectSwipe:(UIButton *)sender 
     { 
     /* I dont know how to put this in code but i would need something like, 
if (the swipe direction is forward and the swipe is > sender.frame){ 
[self ForwardSwipeMethod]; 
    } else if //same thing for right 
    else if //same thing for left 
    else if //same thing for down 

     } 
+0

detectSwipe : 보낸 사람으로 버튼을하지 않는 @selector(detectSwipe:)

콜론은 ":"당신의 방법은 인수를 가지고 있기 때문이다. 인수로 전달되는 제스처 인식기입니다. 또는 인식기가 감지 한 동작과 제스처를 알 수있는 다른 방법은 무엇입니까? –

답변

2

당신은 아마 UISwipeGestureRecognizer를 사용하여 싶어요. UIGestureRecognizer는 일반적으로 서브 클래 싱하지 않는 한 사용하면 안됩니다. 코드는 다음과 유사해야합니다.

UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe)]; 
swipe.direction = UISwipeGestureRecognizerDirectionRight; 
[button addGestureRecognizer:swipe]; 
2

구현하는 방법에 대한 내 생각이다. 대상은 지정된 선택자 메시지를받는 객체이므로 호출은 버튼 하위 클래스에 detectSwipe 메서드를 구현하지 않는 한 self을 인수로 받아 들여야합니다.

+0

전혀 문제가되지 않습니다. 내 대답에 다른 지점을 참조하십시오. –

5

아니요, 정확하지 않습니다. 제스처 인식기의 대상은 버튼이 아니며 제스처를 감지 할 때 action 메소드를 호출하는 객체입니다 (그렇지 않으면 객체가 해당 메소드를 호출하는 방법을 알 수 있습니까? OO에서는 메소드 호출/메시지 보내기에 명시 적 메서드 이름 인스턴스 또는 클래스).

그래서 당신은 가장 가능성 당신은 또한 직접 UIGestureRecognizer 인스턴스하지만 하나를 생성하지 않는

recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; 

을 원하는 것이 경우의 구상 서브 클래스,이 경우 UISwipeGestureRecognizer.

ALLOC - initting 인식기, 당신은 당신이 인식 할 뷰에 첨부 한 후 :

[button addGestureRecognizer:recognizer]; 

는 그 다음 didSwipe에 : 방법, 당신이 결정하는 제스처 인식기의 속성을 사용할 수 있습니다 어떤 크기/스 와이프의 거리/다른 속성이있었습니다.

You better read some docs next time.

1

H2CO3의 답변이 완료되었습니다. 선택기 끝에서 콜론 ":"이 누락되었다는 사실을 잊지 마세요. 그것은 다음과 같이해야합니다 : (UIButton *)sender

관련 문제