Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get indexPath of a uiview on a cell - iOS

I have a view controller with a table view. Each cell has a custom view with a five star rating system. I handle touchesBegan of the view at the class of the view

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self];
    [self handleTouchAtLocation:touchLocation];

}

How can I get the indexPath in order to know on which cell user voted? I don't have a button I have a uiview so I cannot use the following:

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
like image 886
Katerina Avatar asked Dec 11 '22 20:12

Katerina


2 Answers

Do one thing

Give gesture to that view inside cell for row at index path

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedOnView:)];
[singleTap setNumberOfTapsRequired:1];
[singleTap setNumberOfTouchesRequired:1];
[viewnanme addGestureRecognizer:singleTap];

and to handle tap gesture

-(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))
}

Hope this will help to you. :)

like image 125
iDeveloper Avatar answered Dec 28 '22 22:12

iDeveloper


In cellforAtIndexPath keep view's tag as indexPath.row and in below method

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

fetch UItableViewCell according to that view tag

like image 45
Sakshi Avatar answered Dec 28 '22 22:12

Sakshi