Shr*_*hri 30 cocoa-touch objective-c uitableview uiimageview
我正在使用
样式中的UITableViewCell
对象UITableViewCellStyleSubtitle
(即左侧的图像视图,粗体的文本标签以及详细文本标签下的文本标签)来创建我的表格.现在我需要检测触摸UIImageView
并且还要知道单击图像视图的索引路径/单元格.我试过用
cell.textLabel.text = @"Sometext";
NSString *path = [[NSBundle mainBundle] pathForResource:@"emptystar1" ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
cell.imageView.userInteractionEnabled = YES;
Run Code Online (Sandbox Code Playgroud)
但它不起作用.每当点击图像时,都会didSelectRowAtIndexPath:
被调用.我不想创建一个单独的UITableViewCell
并添加自定义按钮.有没有办法检测UIImageView
自己的触摸?
小智 75
在您的cellForRowAtIndexPath
方法中添加此代码
cell.imageView.userInteractionEnabled = YES;
cell.imageView.tag = indexPath.row;
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
tapped.numberOfTapsRequired = 1;
[cell.imageView addGestureRecognizer:tapped];
[tapped release];
Run Code Online (Sandbox Code Playgroud)
然后检查imageView
单击了哪个,检查selector
方法中的标志
-(void)myFunction :(id) sender
{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
NSLog(@"Tag = %d", gesture.view.tag);
}
Run Code Online (Sandbox Code Playgroud)
And*_*rew 18
目前已接受的解决方案在iOS 5.0中被破坏.该错误导致图像视图的手势识别器永远不会被触发.通过对官方开发人员论坛的研究,我发现这是iOS 5.0中的已知错误.它是由导致-gestureRecognizerShouldBegin:
返回NO的内部实现引起的.当您将手势识别器的委托设置为自定义UITableViewCell
子类本身时,会出现该错误.
该补丁是覆盖-gestureRecognizerShouldBegin:
在手势识别的委托,并返回YES.应该在iOS 5.x的未来版本中修复此错误.只要您没有使用新的UITableViewCell复制/粘贴API,这只是安全的.
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return YES;
}
Run Code Online (Sandbox Code Playgroud)
Esq*_*uth 15
对于Swift,在您的cellForRowAtIndexPath方法中添加此代码
cell.imageView?.userInteractionEnabled = true
cell.imageView?.tag = indexPath.row
var tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "TappedOnImage:")
tapped.numberOfTapsRequired = 1
cell.imageView?.addGestureRecognizer(tapped)
Run Code Online (Sandbox Code Playgroud)
然后检查单击了哪个imageView,检查选择器方法中的标志
func TappedOnImage(sender:UITapGestureRecognizer){
println(sender.view?.tag)
}
Run Code Online (Sandbox Code Playgroud)
你可以做的一种方法是从你的图像创建一个UIImageView并添加一个手势识别器.请参阅下面的示例
//Create ImageView
UIImageView *theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"emptystar1.png"]];
theImageView.userInteractionEnabled = YES;
//Add Gesture Recognizer
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageSelectedInTable)];
tapped.numberOfTapsRequired = 1;
[theImageView addGestureRecognizer:tapped];
[cell addSubview:theImageView];
//Memory Cleanup
[tapped release];
[theImageView release];
-(void)imageSelectedInTable
{
NSLog(@"Selected an Image");
}
Run Code Online (Sandbox Code Playgroud)
但是,您现在必须更多地布置您的单元格,因为您不能简单地使用它自己的UIImageView
属性UITableViewCell
.