【问题标题】:UICollectionView cell is null when itemTapped method is executed执行 itemTapped 方法时 UICollectionView 单元格为空
【发布时间】:2015-10-01 13:57:06
【问题描述】:

我正在Xamarin 上开发一个 iOS 应用程序,其中我有两个viewControllers,底部有相同的UICollectionView,其中加载了一个带有快照的列表(类似于一个有 1 行的画廊) .选择第一个 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);

    }

在第二个视图控制器中:

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;

    }

编辑:当我不在 ViewDidAppear 中使用“ItemSelected”方法时,它不会崩溃!

【问题讨论】:

    标签: ios xamarin xamarin.ios uicollectionview uicollectionviewdelegate


    【解决方案1】:

    所以首先这是错误的处理方式。但是崩溃很可能是因为空单元格而发生的。如果单元格不可见,它将为空。您需要先滚动到它。

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

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      相关资源
      最近更新 更多