我有一个连接到我的UITableViewCell类的按钮(动作)。如何从tableViewCell类中获取tableView的indexPath?
@implement myTableViewCell
-(IBAction)buttonPressed{
// Do something to get indexPath?
}
答案 0 :(得分:2)
@property (nonatomic, strong) UIButton *btn;
tableView dataSource文件中的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell.btn addTarget:self action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
}
//button action
-(void)buttonPressed:(UIControl *)sender event:(id)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPos];
if(indexPath != nil){
//to do with indexPath
}
}
//单元格类中的按钮操作
- (void)buttonPressed:(UIButton *)btn event:(id)event{
UIView *superView = [btn superview];
while (superView && ![superView isKindOfClass:[UITableView class]]) {
superView = [superView superview];
}
if ([superView isKindOfClass:[UITableView class]]) {
UITableView *tableView = (UITableView *)superView;
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:tableView];
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPos];
if(indexPath != nil){
NSLog(@"tableView.row:%d", indexPath.row);
}
}
}
答案 1 :(得分:0)
就像这个answer:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
答案 2 :(得分:0)
使用发件人向您的按钮添加操作:
[btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
然后:
- (void) buttonPressed:(id)sender{
CGPoint hitPoint = [sender convertPoint:CGPointZero toView:tableView];
NSIndexPath *hitIndex = [tableView indexPathForRowAtPoint:hitPoint];
}
答案 3 :(得分:0)
从单元格中获取表格。把它放在牢房里面
- (UITableView*)tableView {
if (tableView == nil) {
tableView = (UITableView*)self.superview;
while (tableView && ![tableView isKindOfClass:[UITableView class]]) {
tableView = (UITableView*)tableView.superview;
}
}
return tableView;
}
请求索引路径
NSIndexPath *p = [self.tableView indexPathForCell:self];
TADA;)