gpt4 book ai didi

ios - 使用 UIButton 转接 TableViewCell

转载 作者:行者123 更新时间:2023-12-01 17:41:59 25 4
gpt4 key购买 nike

我的表格 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com