我有一个带有表视图的视图控制器。每个单元格都有一个带五星评级系统的自定义视图。我在视图的类中处理视图的touchesBegan
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:self];
[self handleTouchAtLocation:touchLocation];
}
如何获取indexPath以了解哪个用户投票?我没有按钮我有一个uiview所以我不能使用以下内容:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
答案 0 :(得分:9)
做一件事
在索引路径
的行中为单元格内的视图提供手势UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedOnView:)];
[singleTap setNumberOfTapsRequired:1];
[singleTap setNumberOfTouchesRequired:1];
[viewnanme addGestureRecognizer:singleTap];
并处理点击手势
-(void)tappedOnView:(UITapGestureRecognizer *)gesture
{
CGPoint location = [gesture locationInView:tableView];
NSIndexPath *ipath = [tableView indexPathForRowAtPoint:location];
UITableViewCell *cellindex = [tableView cellForRowAtIndexPath: ipath];
}
Swift 3+
var singleTap = UITapGestureRecognizer(target: self, action: #selector(self.tappedOnView))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
viewnanme.addGestureRecognizer(singleTap)
func tapped(onView gesture: UITapGestureRecognizer) {
let location: CGPoint = gesture.location(in: tableView)
let ipath: IndexPath? = tableView.indexPathForRow(at: location)
let cellindex: UITableViewCell? = tableView.cellForRow(at: ipath!)
}
Swift 4 +
var singleTap = UITapGestureRecognizer(target: self, action:
#selector(self.tappedOnView))
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
viewnanme.addGestureRecognizer(singleTap)
func tapped(onView gesture: UITapGestureRecognizer)
{
let location: CGPoint = gesture.location(in: tableView)
let ipath: IndexPath? = tableView.indexPathForRow(at: location)
let cellindex: UITableViewCell? = tableView.cellForRow(at: ipath ??
IndexPath(row: 0, section: 0))
}
希望这会对你有所帮助。 :)
答案 1 :(得分:2)
在cellforAtIndexPath
中将视图的标记保留为indexPath.row
,并在以下方法中
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
根据该视图标记
获取UItableViewCell
答案 2 :(得分:1)
通过在视图的类中创建属性,可以在cellForRowAtIndexPath:
中创建视图时将索引路径存储在自定义视图中。可以在init中为自定义视图设置该属性。然后,通过阅读属性,您的touchesBegan:withEvent:
方法将可以使用索引路径。
答案 3 :(得分:0)
UITableView有一个给定的委托方法,即cellForRowIndexPath:。 您无需在代码中添加任何Tap Gesture或touchesBegan:方法。 TableView已经有了这个。您可以在此方法cellFor RowIndexPath中获取所选单元格的索引路径:。