如何在cell-iOS上获取uiview的indexPath

如何在cell-iOS上获取uiview的indexPath,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我有一个带有表视图的视图控制器。每个单元格都有一个带有五星评级系统的自定义视图。我在视图类中处理视图的接触 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint touchLocation = [touch locationInView:self]; [self handleTouchAtLoc

我有一个带有表视图的视图控制器。每个单元格都有一个带有五星评级系统的自定义视图。我在视图类中处理视图的接触

    - (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];

cellforrowatinexpath:
中创建视图时,通过在视图类中创建属性,可以在自定义视图中存储索引路径。可以在自定义视图的init中设置该属性。然后,通过读取属性,索引路径将在您的
touchesbeated:withEvent:
方法中可用。

cellforAtIndexPath
中,将视图的标记保留为
indexPath.row
和在下面的方法中

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

根据视图标记获取
UItableViewCell
UITableView有一个给定的委托方法,即cellForRowIndexPath:。 无需在代码中添加任何点击手势或触摸开始:方法。TableView已经有了这个。您可以在此方法cellFor RowIndexPath:中获取所选单元格的索引路径。

做一件事

为位于索引路径的行的单元格内的视图提供手势

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!)
}
斯威夫特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))
}

希望这对您有所帮助。:)

正确的方法是在cell类中处理您的触摸,并使用委托将信息传递回tableview-在Swift中有一个类似的答案,我认为您应该创建一个属性来保存该信息。