0

I'm developing an iOS app on Xamarin, in which I have two viewControllers with the same UICollectionView at the bottom, in which a List with snapshots is loaded (something like a gallery with 1 row). After a snapshot from the 1st viewController is selected, I go to the 2nd viewController and I want the snapshot to be PreSelected when the viewController is loaded, but I'm receiving System.NullReferenceException, just a second after the screen is loaded. Any ideas why?

Here in 1st viewController:

I'm saving the indexPath in a helper class and manage the transition to 2nd with NotificationCenter.

public void ItemSelected (UIKit.UICollectionView collectionView, Foundation.NSIndexPath indexPath)
    {
        UICollectionViewCell cell = collectionView.CellForItem (indexPath);
        var newImage = (UIImageView)cell.ViewWithTag (100);
        var selectedBgView = new UIView (cell.Bounds);
        cell.SelectedBackgroundView = selectedBgView;
        cell.SelectedBackgroundView.BackgroundColor = UIColor.Orange;
        ApplicationState.Instance.TappedSnapshot = AppUtils.UIImageToBase64 (newImage.Image); 

        ApplicationState.Instance.SnapshotIndexPath = collectionView.IndexPathForCell (cell); 


        NSNotification notif = NSNotification.FromName ("imageTapped", this);
        NSNotificationCenter.DefaultCenter.PostNotification (notif);

    }

In 2nd viewController:

public override void ViewDidAppear (bool animated)
    {
        base.ViewDidAppear (animated);
        CollectionView.SelectItem (ApplicationState.Instance.SnapshotIndexPath, true, UICollectionViewScrollPosition.Right);
        this.ItemSelected (CollectionView, ApplicationState.Instance.SnapshotIndexPath);
    }

public void ItemSelected (UIKit.UICollectionView collectionView, Foundation.NSIndexPath indexPath)
    {
        UICollectionViewCell cell = collectionView.CellForItem (indexPath);
        var selectedBgView = new UIView (cell.Bounds);
        cell.SelectedBackgroundView = selectedBgView;
        cell.SelectedBackgroundView.BackgroundColor = UIColor.Orange;

    }

EDIT: When I don't use the "ItemSelected" method in ViewDidAppear, it isn't crashing!

P.Todorov
  • 43
  • 10

1 Answers1

0

So first off this is the wrong way to handle this. But the crash is most likely happening because of a null Cell. If the Cell isn't visible it will be null. You need to scroll to it first.

What you should do is have a parent view controller that has the collection view on the bottom. Your top part of the view would hold the data that switches. When you navigate, switch just the top content rather than creating a new collection view.

Clancey
  • 333
  • 1
  • 6