一、做项目时用到自定义单元格,且单元格中有按钮,项目功能扩展需要点击按钮在每一个单元格的后面增加一个视图,因此需要确定单元格的indexPath属性,然后根据每一个单元格的高度就可以确定每一个单元格的位置,因此就可以增加新的视图,该问题的关键是点击按钮后确定所在单元格的索引,这个时候就要用到一个非常重要的属性indexPathForRowAtPoint。
- (void)btnClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
}
又或者是添加手势的视图
-(void)clickCommentLabelAction:(UIGestureRecognizer *)gestureRecognizer {
CGPoint currentTouchPosition=[gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath=[self.tableView indexPathForRowAtPoint:currentTouchPosition];
[self creatInputBox:indexPath];
}
二、单元格中有UITextField或者其他控件
首先想到的也是通过event事件来确定UITextField的所在位置,例如:
@IBAction func textFieldDidChanged(_ sender: UITextField, forEvent event: UIEvent) {
}
@IBAction func textFieldDidBegin(_ sender: UITextField, forEvent event: UIEvent) {
}
但是经过测试,事件发生时传递过来的event对象为0x00000000,即该对象是不能用的,因此不能通过该方法来确定所在单元格的索引。
解决方案:通过获取UITextField父视图的方法来获取它所在的单元格,然后通过单元格的坐标即可计算出所在单元格的索引
if let currentCell = editingTextField?.superview.superview as? UITableViewCell {
let indexPath = tableView.indexPathForRow(at: currentCell.center)
//或者let indexPath = tableView.indexPath(for: currentCell)
}