ios - 使用 UIButton 转接 TableViewCell

标签 ios uitableview uistoryboardsegue

我的表格 View 中有一个带有按钮的自定义位置单元格。当我按下按钮时,我希望它与该位置的啤酒细节保持一致。我正在使用 Storyboard ,我可以通过使用以下代码将整个单元格连接到 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 + 将 Storyboard 中的一个 segue 从 TableView 拖到 DetailView 并将 segue 命名为“beer”,并且我在单元格中有一个名为“beerTaps”的按钮,但无论我点击哪一行,我仍然只能获得第 1 行的详细信息。

最佳答案

如果您将 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;
    }
}

通常最好不要使用按钮在 View 层次结构中的位置来获取单元格。更好的方法是在 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;
    }
}

关于ios - 使用 UIButton 转接 TableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16225518/

相关文章:

ios - 滚动时保持 UITableViewCells 的选定状态

ios - UITableView 在事件时不会更新

ios - Swift 如何在按钮单击时显示 Tabbar

iOS Storyboarding - 实践经验 re : multiple developers?

ios - iOS (iPhoneX) 上的 html5 视频播放

ios - 删除图表上线上的折线图值

ios - Pan Gesture 的动画从初始状态而不是当前状态开始

ios - 在 uitableviewcell 中自定义 uipickerview

ios - Cocos2D 游戏场景中 CCSpriteBatchNode 和纹理表的最佳方法是什么

ios - 在 Touch ID block 内调用 PerformSegue 后应用程序停止