【问题标题】:trying to load a picture into new ViewController from didSelectCellAtIndex试图从 didSelectCellAtIndex 将图片加载到新的 ViewController
【发布时间】:2015-07-12 17:44:27
【问题描述】:

我有一个 CollectionView,在 didSelectItemAtIndexPath 方法中我实例化了一个新的 ViewController,设置 ViewController 上的 String 属性来保存图像的名称。然后在新 ViewController 中的 viewDidLoad 或 viewDidAppear 方法中,我尝试使用 vc.imageName 属性设置图像。

代码如下:

// collection.m


    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        ViewController *vc = [[ViewController alloc] init];

        NSString *imageName = [colouringPhotos objectAtIndex:indexPath.row];
        vc.imageName = imageName;
        [self presentViewController:vc animated:YES completion:nil];
    }


// ViewController.h

@property (nonatomic, strong) NSString * imageName;

//ViewController.m

@property (strong, nonatomic) IBOutlet UIImageView *lineImageView;

-(void) viewDidAppear:(BOOL)animated{
    self.lineImageView.image = [UIImage imageNamed:self.imageName];
}

但图片不显示。我已经在 ImageView 上设置了背景颜色,以检查它是否显示在新的 ViewController 中,我可以看到它,但图像永远不会显示在 UIImageView 中。

【问题讨论】:

  • 是的,当我在 viewDidLoad 中设置断点时,名称为空。所以名称没有被传递给新的 ViewController
  • 如果我在 vc.imageName = imageName 处设置断点,我可以看到 imageName 在那里,但是一旦它被传递给 presentViewcontroller,它在 viewDidLoad 方法中为空

标签: ios uiviewcontroller uicollectionview


【解决方案1】:

您可以使用 Segue 来显示下一个视图控制器。假设您使用“ShowNextViewController”作为 Segue 的标识符,您可以使用 prepareForSegue:sender: 设置目标视图控制器的 imageName 属性:

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

    if ([segue.identifier isEqualToString:@"ShowNextViewController"]) {
        ViewController *destination = (ViewController *)segue.destinationViewController;
        NSIndexPath *selectedIndex = [[self.collectionView indexPathsForSelectedItems] firstObject];
        destination.imageName = self.colouringPhotos[selectedIndex.row];
    }
}

如果您在设置 segue 时遇到问题,请参阅 this iOS Developer Library document 了解更多信息。

另外,请参阅UIViewController Class Reference,了解有关prepareForSegue:sender: 方法的更多信息。

【讨论】:

  • 太棒了——我刚刚实现了 prepareForSegue 方法,但缺少 selectedIndex 行。谢谢一百万。
  • 没问题。我很高兴能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多