簡體   English   中英

從視圖控制器檢測觸摸是否在移動的UIImageView上

[英]Detect if a touch is on a moving UIImageView from a View Controller

我有一個UIViewController,它使用touchesBegan檢測觸摸事件。 屏幕上漂浮着移動的UIImageView對象,我需要查看一下觸摸事件是否落在其中之一上。 我正在嘗試:

UITouch* touch = [touches anyObject];

if ([arrayOfUIImageViewsOnScreen containsObject: [touch view]]) {
    NSLog(@"UIImageView Touched!");
}

但這永遠不會發生。 另外,如果我要做這樣的事情:

int h = [touch view].bounds.size.height;
NSLog([NSString stringWithFormat: @"%d", h]);

它每次都會輸出整個UIViewController(屏幕)的高度,即使我觸摸了其中一個UIImageViews,也很明顯[touch view]並沒有提供UIImageView。 當僅按下UIImageView時如何檢測? 請不要建議使用UIButtons。

謝謝!

如果只想檢測何時按下UIImageView,請檢查該類:

if (touch.view.class == [UIImageView class]) {
    //do whatever
}
else {
    //isnt a UIImageView so do whatever else
}

編輯 - -

您尚未將UIImageView的userInteraction設置為啟用嗎?

我知道您說過,請不要建議使用UIButtons,但是按鈕聽起來對我來說是最好/最簡單的方法。

您可以嘗試通過觸摸之一將hitTest消息發送到主視圖的CALayer-它會返回您所觸摸的子視圖層次結構最下方的CALayer。

然后,您可以測試以查看您觸摸的圖層是否是其中一個UIImageView的圖層,然后從此處繼續。

此代碼使用從UIGestureRecognizer生成的點。

CGPoint thePoint = [r locationInView:self.view];
thePoint = [self.view.layer convertPoint:thePoint toLayer:self.view.layer.superlayer];
selectedLayer = [self.view.layer hitTest:thePoint];

如果要檢查觸摸方式,請使用CGRectContainsPoint。

1.捕獲觸摸事件並獲取觸摸點,

2.制作一個CGRect來界定要檢查觸摸事件的對象,

3.使用CGRectContainsPoint(CGRect,CGPoint)並捕獲布爾返回值。

http://developer.apple.com/library/ios/#DOCUMENTATION/GraphicsImaging/Reference/CGGeometry/Reference/reference.html

這是CGRect的類參考。

忘記了這個問題-問題是我沒有等到viewDidLoad在UIImageView上設置userInteractionEnabled。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM