1

我的表格视图中有一个带有按钮的自定义位置单元格。当我按下按钮时,我希望它与该位置的啤酒细节保持一致。我正在使用情节提要,我可以通过使用以下代码将整个单元格连接到 BeerTableViewController 来使其工作

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if([[segue identifier] isEqualToString:@"beer"]){
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        BeerTableViewController *beer = (BeerTableViewController *)[segue destinationViewController];
        Location *location = [self.location_results objectAtIndex:indexPath.row];
        beer.location_id = location.location_id;
        beer.location_name = location.location_name;
        }

}

但是当我从按钮而不是整个单元格创建一个转场时,无论单击哪一行,它总是与第一行转场。显然,我不会在按下按钮的情况下通过该行。我在这里查看了许多解决方案,但没有找到明确的答案。有任何想法吗?

编辑 1

我正在 TableViewController 中尝试以下代码

-(void)beerTapsPressed:(id)sender {
    UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
    NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
    [self performSegueWithIdentifier:@"beer" sender:clickedButtonPath];

}

我有 ctrl + 将情节提要中的一个 segue 从 TableView 拖到 DetailView 并将 segue 命名为“beer”,并且我在单元格中有一个名为“beerTaps”的按钮,但无论我点击哪一行,我仍然只能获得第 1 行的详细信息。

4

2 回答 2

4

如果您将 segue 连接到按钮,这应该可以工作:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([[segue identifier] isEqualToString:@"beer"]) {
        UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
        NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
        BeerTableViewController *beer = (BeerTableViewController *)[segue destinationViewController];
        Location *location = [self.location_results objectAtIndex:clickedButtonPath.row];
        beer.location_id = location.location_id;
        beer.location_name = location.location_name;
    }
}

通常最好不要使用按钮在视图层次结构中的位置来获取单元格。更好的方法是在 cellForRowAtIndexPath 中为按钮提供一个等于 indexPath.row 的标签。然后在 prepareForSegue 中,你可以这样做:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender {
    if([[segue identifier] isEqualToString:@"beer"]) {
        BeerTableViewController *beer = (BeerTableViewController *)[segue destinationViewController];
        Location *location = [self.location_results objectAtIndex:sender.tag];
        beer.location_id = location.location_id;
        beer.location_name = location.location_name;
    }
}
于 2013-04-25T23:55:44.960 回答
2

您可以在 tableview 控制器和目标控制器之间连接 segue,然后在有人点击按钮时调用 performSegueWithIdentifier。至于传达点击按钮的单元格的 indexPath ,您可以使用如下内容:

-(void)buttonPressed:(id)sender {
 UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
 NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];


}

您还可以设置按钮的 tag 属性以知道是哪一个,但如果您的表格中有多个部分,这会变得很难看。如果您确实使用该方法,您将需要确保在重复使用单元格时重置标签......

于 2013-04-25T22:21:38.620 回答