Objective-C / UIGestureRecognizer 를 이용해서 이미지에 Pinch 액션을 넣었을 때 팝업 띄우기
step 1
우선 storyboard 에서 UIImageView 객체를 하나 집어넣고 적당힌 이미지를 입힌 다음 객체 속성에서 User Interaction Enabled를 체크해 준다.
그 다음 UIImageView 객체를 헤더 파일로 우클릭-드래그 해서 property로 선언하고 pinchGestureImage 로 이름짓는다.
이것으로 스토리보드에서 할일은 끝.
step 2
다음은 헤더에서 프로퍼티와 터치 입력이 발생했을 때 사용할 메서드를 선언해준다.
ViewController.h
--
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *pinchGestureImage; //터치 제스쳐가 일어날 UIImageView
@property UIAlertView *myAlert; //액션이 일어났을 때 보여줄 팝업창
-(void)pinchEnabled:(UIPinchGestureRecognizer *)recognizer; //이미지를 핀치했을때 동작할 메서드
@end
--
step 3
다음은 구현부에서 메서드를 정의해준다.
(XCode에서 자동으로 생성하는 부분-[super viewDidLoad] 등-은 제외함)
ViewController.m
--
//property 들을 synthesize 해준다.
@synthesize pinchGestureImage;
@synthesize myAlert;
-(void)pinchEnabled:(UIPinchGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateBegan) //UIPinchGestureRecognizer 객체의 상태가 '시작'상태일 때
{
myAlert = [[UIAlertView alloc]initWithTitle:nil message:@"Hello!" delegate:nil cancelButtonTitle:@"close" otherButtonTitles:nil, nil]; //팝업창의 속성을 이와 같이 정의하고
[myAlert show]; //팝업을 띄운다
}
}
- (void)viewDidLoad {
UIPinchGestureRecognizer *myPinchGesture = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchEnabled:)]; //myPinchGesture 라는 터치 제스쳐를 하나 만들고 init하면서 target은 self, 제스쳐를 입력받아 동작한다면 pinchEnabled: 메서드를 따르도록 한다.
[pinchGestureImage addGestureRecognizer:myPinchGesture]; //myPinchGesture를 pinchGestureImage에 심는다.
}
@end
--
이제 시뮬레이터에서 앱을 빌드하면 아래와 같은 화면이 보인다.
그리고 이미지를 pinch 하면 팝업이 동작한다.
UIPinchGestureRecognizer 를 UILongTabRecognizer 등으로 교체하여 롱탭, 탭 등의 다른 제스쳐로도 응용 가능함.