执行itemTapped方法时,UICollectionView单元格为null

时间:2015-10-01 13:57:07

标签: ios xamarin xamarin.ios uicollectionview uicollectionviewdelegate

我正在Xamarin开发一个iOS应用,其中我有两个viewControllers,底部有相同的UICollectionView,其中加载了带快照的列表(像一排画廊的东西)。选择第一个viewController的快照后,我转到第二个viewController,我希望在加载viewController时快照为 PreSelected ,但我收到System.NullReferenceException,加载屏幕后一秒钟。有什么想法吗?

这里是第一个viewController:

我将indexPath保存在帮助程序类中,并使用NotificationCenter管理向2nd的转换。

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);

    }

在第二个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;

    }

编辑:当我不使用" ItemSelected" ViewDidAppear中的方法,它不会崩溃!

1 个答案:

答案 0 :(得分:0)

首先,这是处理此问题的错误方法。但是崩溃很可能是因为一个空单元格而发生的。如果Cell不可见,则它将为null。你需要先滚动它。

您应该做的是拥有一个父视图控制器,其底部有集合视图。视图的顶部将保留切换的数据。导航时,只切换顶部内容,而不是创建新的集合视图。