使用UIButton查看TableViewCell

时间:2013-04-25 22:03:40

标签: ios uitableview uistoryboardsegue

我的tableview中有一个自定义位置单元格,带有一个按钮。当我按下按钮时,我希望它能够切换到该位置的啤酒细节。我正在使用故事板,我可以通过使用以下代码将整个单元格连接到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;
        }

}

但是当我从按钮而不是整个单元格创建一个segue时,无论点击哪一行,它总是与第一行划分。很显然,我没有按下按钮传球。我在这里看了很多解决方案而没有找到明确的答案。有任何想法吗?

编辑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行的详细信息,无论哪一行我点击了。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

您可以在tableview控制器和目标控制器之间连接segue,然后当有人点击按钮时,您可以调用performSegueWithIdentifier。至于传递按钮被按下的单元格的indexPath,你可以使用这样的东西:

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


}

您还可以设置按钮的tag属性以了解哪一个,但如果您的表中有多个部分,则会变得很难看。如果您确实使用了这种方法,那么您也需要确保在重复使用单元格时重置标记...