【问题标题】:iOS - TableView - Get Index of Header section on tapping buttoniOS - TableView - 在点击按钮上获取标题部分的索引
【发布时间】:2014-05-08 10:40:48
【问题描述】:

我已经为 UITableView 实现了自定义标题部分。 Header 的自定义视图中有一个按钮,我想在该按钮的点击操作上获取该部分的索引。

我可以试试

CustomHeader *view = (CustomHeader*)btnObject.superView;

但是如何从这个 headerView 的实例中获取该部分的 IndexPath 或索引?

编辑: 我需要一些独立于标签的东西或任何类似于 Cell 的 indexpath 的东西,如下所示

-(NSIndexPath*)indexPathFromSenderView:(UIView*)view{

    CGPoint center= view.center;
    CGPoint rootViewPoint = [view.superview convertPoint:center toView:self.tblMainContainer];
    NSIndexPath *indexPath = [self.tblMainContainer indexPathForRowAtPoint:rootViewPoint];
    return indexPath;
}

【问题讨论】:

  • 您可以为自定义标题视图分配一个标签,并在按下按钮时获取该标签。
  • 不,但是如果我们以某种方式删除该部分怎么办?那么就会出现不一致。
  • 在重新加载表时,viewForHeaderInSection: 将再次被调用,因此标签将被重新分配。因此,如果您在删除该部分后重新加载表格,它应该可以工作。
  • 如果标签(标准 int 或自定义 id)不适合您,总有一个选项可以不使用标题,而是在需要时添加一个额外的单元格,然后您可以使用您的indexPathFromSenderView:.
  • 是的 Yogi 我同意你的观点,但是如果表格有大约 10-15 行的图像并且可能是一些庞大的内容怎么办?那么重新加载整个表只是为了重新分配标签并删除一行是否合适?

标签: ios objective-c uitableview nsindexpath


【解决方案1】:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    // create custom header here

    // set up a button method
    [yourButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

    // set the button tag as section
    yourButton.tag = section;

    return yourCustomHeaderWithButton;
}


later


-(void)buttonAction:(id)sender{

    UIButton *clickedButton = (UIButton*)sender;
    NSLog(@"section : %i",clickedButton.tag);

}

【讨论】:

  • 但是如果要删除该部分,那么它会导致崩溃。
  • 没有。首先测试它并让我知道。即使删除了行,它也会起作用。删除行后,通过 reloaddata 方法调用重新加载数据。就是这样
  • 我在做同样的事情,但它崩溃了。因为在删除特定部分时它永远不会更新其他部分标签,非常明显
【解决方案2】:

您需要使用标签。与普通单元格不同,无法从标题部分获取 indexPath。如果需要,您可以将标题部分视图改为 UITableViewCell 行,然后将其添加为部分的顶行。

顺便说一句,你可以使用

[self.tableView indexPathForCell:cell]

而不是获取单元格的索引路径。

如果您决定使用标签,您可以通过在您的操作方法中使用以下代码来更新标签值:

[UIView animateWithDuration:0.2 animations:^{
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionToDelete] withRowAnimation:UITableViewRowAnimationAutomatic];
    } completion:^(BOOL finished){
        [self.tableView reloadData];
    }];

这将防止标签值错误并阻止您的应用程序崩溃。

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2020-04-24
    • 2019-05-24
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多