【问题标题】:How to pass value from a selected cell in embedded collectionView to another viewController?如何将嵌入式collectionView中选定单元格的值传递给另一个viewController?
【发布时间】:2017-08-30 17:50:05
【问题描述】:

UIViewController 1,我设置了一个数组。这个UIViewController 转为UIViewController 2

UIViewController 2 中,有一个带有自定义UITableViewCellUITableView。还有一个UIButton 可以很好地返回UIViewController 1

在自定义单元格中,有一个collectionView。这是由来自ViewController 1 的数组填充的。

我的问题是,当在collectionViewUIViewController 2 - 自定义UITableViewCell 类)中选择一个项目时,如何将该值一直传递回UIViewController 1

如果这是重复的,我很抱歉。我在这里提到了许多类似的条目,但似乎没有任何效果。我也试过这个:

http://www.appcoda.com/ios-collection-view-tutorial/

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if ([segue.identifier isEqualToString:@"showRecipePhoto"]) {
    NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
    RecipeViewController *destViewController = segue.destinationViewController;
    NSIndexPath *indexPath = [indexPaths objectAtIndex:0];
    destViewController.recipeImageName = [recipeImages[indexPath.section] objectAtIndex:indexPath.row];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
  }
}

我不断收到返回的空值,但我不知道为什么。

(我没有使用故事板。这是我第一次尝试任何类型的编程。希望有任何意见!)

【问题讨论】:

    标签: ios objective-c uitableview uicollectionview


    【解决方案1】:

    您可以使用UICollectionViewDelegate

    加入你的班级:

    class YourViewController: UIViewController, UICollectionViewDelegate { ... }
    

    并使用- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath当单元格被选中时调用该事件;您必须将值保存在属性中;像这样:

    - (void)collectionView:(UICollectionView *)collectionView 
    didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
    {
       selectedRecipeImageName = [recipeImages[indexPath.section] objectAtIndex:indexPath.row];
    ... 
       [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
    }
    

    然后:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
      if ([segue.identifier isEqualToString:@"showRecipePhoto"]) {
        RecipeViewController *destViewController = segue.destinationViewController;
        destViewController.recipeImageName = selectedRecipeImageName
      }
    }
    

    【讨论】:

    • 是的。如此简单,但当时我无法理解它。顺便说一句,很抱歉延迟回复。我在一边做这个。谢谢!
    【解决方案2】:

    您可以使用委托或完成块来完成。

    要解决委托问题,请关注link

    要解决完成块,请关注link

    【讨论】:

    • 欢迎来到 SO。请避免仅链接作为答案。如果您认为这个问题已经得到解答,您可以使用“标记”按钮将其标记为重复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2021-11-19
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多