2009-12-04 152 views
0

如何確定我在屏幕上觸摸的是什麼UIImageView?例如,我在UIView中添加了10x10平鋪的UIImageView。現在在觸摸開始,我怎麼能知道我在屏幕上觸摸的圖像?我應該在這個實現中使用hitTest方法嗎?UIImageView觸摸事件

謝謝。

回答

2

我通常會發現最簡單的方法是繼承UIImageView並添加我自己的觸摸事件處理程序。

事實上,我經常做的是創建一個UIImageView的子類,唯一的目的是允許另一個類作爲下一個響應者。這樣我就不必爲任何情況而劃分子類。如果你需要大量的這些視圖,那麼這是唯一值得做的事情,而且你還沒有對它們進行子類化。

0

這個問題在這裏被問了很多次。嘗試下次使用搜索。我通常使用自定義樣式的UIButton來做你想做的事。這樣的變體爲您提供了標準的方法來捕捉觸摸而不需要子類化。

0

要跟進UIButton建議,下面是我爲UIButton所做的一個片段,該片段以UIImage呈現。

這是用於跟蹤得到了UITableViewCell內所觸摸的特定UIButton圖像類型,並沿此UIButton放在行和部分而過:

UIButton *_infoButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)]; 
[_infoButton setImage:[UIImage imageNamed:@"Info.png"] forState:UIControlStateNormal]; 
[_infoButton setTitle:[NSString stringWithFormat:@"%d:%d", indexPath.section, indexPath.row] forState:UIControlStateReserved]; 
[_infoButton addTarget:self action:@selector(touchedDetailedInfoButton:) forControlEvents:UIControlEventTouchDown]; 
// ... 
[ _infoButton release]; 

下面是用於恢復相關的方法標題和做一些有趣的事情吧:

- (void) touchedDetailedInfoButton:(NSString *)title { 
    unsigned int _section, _row; 
    const char * _indexPathCharPtr = [title cStringUsingEncoding:NSUTF8StringEncoding]; 
    sscanf(_indexPathCharPtr, "%d:%d", &_section, &_row); 
    NSUInteger _path[2] = {_section, _row}; 
    NSIndexPath *_touchedIndexPath = [[NSIndexPath alloc] initWithIndexes:_path length:2]; 
    [self doSomethingInterestingWithIndexPath:_touchedIndexPath]; 
    [_touchedIndexPath release]; 
} 

很可能有更簡單的方法去了解這一點,所以希望別人來沿,並提供一種替代(比subcla其他也是UIImageView,這也是一個非常有效的選擇)。