我想構建一個自定義表格視圖單元格,並在其中放置一個imageview,當用戶單擊imageview以在視圖控制器上彈出一個視圖時 - 視圖將會知道該圖像被按下的單元格。iPhone - 從自定義單元中捕捉uiimageview觸摸事件
THX
我想構建一個自定義表格視圖單元格,並在其中放置一個imageview,當用戶單擊imageview以在視圖控制器上彈出一個視圖時 - 視圖將會知道該圖像被按下的單元格。iPhone - 從自定義單元中捕捉uiimageview觸摸事件
THX
使用UITapGestureRecognizer
手勢檢測來自UIView
繼承的任何視圖的觸摸。
如下使用.....
添加敲擊手勢UITapGestureRecognizer
到myImageView
視圖(類型的UIImageView
)。
UITapGestureRecognizer *myTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureTapEvent:)];
myImageView.userInteractionEnabled = YES;
[myImageView addGestureRecognizer:myTapGesture];
[myTapGesture release];
實施gestureTapEvent:
接收觸摸事件的方法。
-(void)gestureTapEvent:(UITapGestureRecognizer *)gesture
{
}
更新:
與您連接使用的UIGestureRecognizer
view
財產手勢,你可以訪問視圖。
@property(nonatomic, readonly) UIView *view;
所以你的gestureTapEvent方法應該像下面那樣。
-(void)gestureTapEvent:(UITapGestureRecognizer *)gesture
{
UIImageView* myImageView = (UIImageView*)gesture.view ;
}
你有多種可能性爲:
UITapGestureRecognizer
(我建議這個解決方案)touchesBegan:withEvent:
方法等例子:
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClicked:)];
[cell.yourImageView addGestureRecognizer:gestureRecognizer];
[gestureRecognizer release];
[編輯]
然後,當你實現你的imageViewClicked
方法,您可以使用GestureRecognizer的view
屬性來獲取抽頭ImageView的。從開始,例如,您可以:
tableView:cellForRowAtIndexPath:
方法的影響的話)來檢索標籤,做任何你想做的事情(取決於它影響到什麼,例如你可能已經在tableView:cellForRowAtIndexPath:
中設置了imageView.tag = indexPath.row
,然後得到那個indexPath行)例子:
-(void)imageViewClicked:(UITapGestureRecognizer*)gestRecognizer
{
UIImageView* iv = (UIImageView*)gestRecognizer.view;
NSInteger tag = iv.tag; // then do what you want with this
// or get the cell by going up thru the superviews until you find it
UIView* cellView = iv;
while(cellView && ![cellView isKindOfClass:[UITableViewCell class]])
cellView = cellView.superview; // go up until you find a cell
// Then get its indexPath
UITableViewCell* cell = (UITableViewCell*)cellView;
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
}
但我怎麼知道在tap方法中點擊了哪個imageview? – yosifz8
你必須跟蹤indexPath.row – Maulik
UIGestureRecognizer的'view'屬性(作爲參數傳遞給你的'imageViewClicked:'選擇器)將允許你訪問UIImageView。然後,您可以使用imageView的標籤來跟蹤objet或indexPath與哪個模型相關聯(如果您在返回單元格時設置標籤)或獲取父UITableViewCell並索要其indexPath。 (我會更新我的答案給代碼) – AliSoftware
相反的UIImageView,你可以自定義需要的UIButton和相同的圖像分配到按鈕,你會得到這個按鈕的touchupInside事件。只需指定button.tag = indexpath.row,以便您可以獲取按下哪個單元格的按鈕。
-(IBAction)ButtonPressed:(id)sender{
UIButton *btnSelected = sender;
switch(btnSelected.tag){
case: 0
///Cell 0's Button Pressed.
break;
......
......
}
希望得到這個幫助。
要添加的觸摸事件,以一個UIImageView使用以下格式在您的m
UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(newTapMethod)];
[_imageButtonName setUserInteractionEnabled:YES];
[_imageButtonName addGestureRecognizer:newTap];
然後創建newTapMethod(或你的名字什麼都)
-(void)newTapMethod{
//...
}
希望幫助。
但我怎麼知道在tap方法中點擊了哪個imageview? – yosifz8
@ yosifz8:檢查更新後的答案... – Jhaliya