2011-10-03 91 views
0

我有一個ImageView,我希望當用戶按下圖像視圖以顯示一條消息作爲警報。我應該使用什麼方法?你能爲我提供一個例子嗎?UIImageView觸摸時顯示UIAlert

在此先感謝..

+0

使用UITapGestureRecognizer的 – Narayana

+0

在.h UIGestureRecognizerDelegate – Narayana

回答

5

添加UITapGestureRecognizer:

imageView.userInteractionEnabled = YES; 
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handleTap:)]; 
[imageView addGestureRecognizer:tapRecognizer]; 
[tapRecognizer release]; 

然後回調...

- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer 
{ 
    //show your alert... 
} 
+0

我在這一行發出警告:tapRecognizer.delegate = self; – Gabrielle

+0

我編輯了答案,這不是必需的。 – ender

1

使用觸摸事件的方法做烏爾任務

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

    UITouch *touch = [[event allTouches] anyObject]; 

    CGPoint location= [touch locationInView:self.view]; 

    if(CGRectContainsPoint(urImageView.frame, location)) { 
     //AlertView COde 
    } 
} 
+0

如何設置一個圖像視圖的觸摸事件? – Gabrielle

+0

我給出了示例代碼 –

0

使用觸摸委託方法,找到你的圖像視圖那裏,

1

如果你不原意子類UIImageView覆蓋觸摸事件方法 - 或者實現ViewController中的觸摸方法,並檢查觸摸幀位於圖像視圖幀 - 你可以(這可能更容易)添加一個UITapGestureRecognizer到你的UIImageView

See here in the documentation更多細節

UITapGestureRecognizer* tapGR = [[UITapGestureRecognizer alloc] 
    initWithTarget:self action:@selector(tapOnImage:)]; 
[yourImageView addGestureRecognizer:tapGR]; 
[tagGR release]; 

然後實現-(void)tapOnImage:(UIGestureRecognizer*)tapGR方法,如你所願

1
UITapGestureRecognizer *singleTapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)]; 
    singleTapOne.numberOfTouchesRequired = 1; singleTapOne.numberOfTapsRequired = 1; singleTapOne.delegate = self; 
[self.view addGestureRecognizer:singleTapOne]; [singleTapOne release]; 


- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer 
1

首先, 啓用財產

yourImgView.setUserInteractionEnabled = TRUE; 

然後應用在viewDidLoad中下面的代碼;

UITapGestureRecognizer *tapOnImg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnImgView:)]; 
tapOnImg.numberOfTapsRequired = 1; tapOnImg.delegate = self; 
[yourImgView addGestureRecognizer:tapOnImg]; 
0

而不是使用UITapGestureRecognizer如果其中有您的ImageView覆蓋類UIResponder你可以只覆蓋touchesBegan

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
     UITouch *touch = [touches anyObject]; 
     if ([touch view] == YOUR_IMAGE_VIEW) { 
      // User clicked on the image, display the dialog. 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Image Clicked"  message:@"You clicked an image." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
      [alert show]; 
      [alert release]; 
     } 
} 

您必須確保userInteractionEnabledYES您的圖像視圖。