如何在UICollectionView中单击自定义单元格时触发segue

Ror*_*san 2 xamarin.ios ios xamarin

当我的自定义单元格UICollectionView突出显示时,我正在尝试对详细视图控制器执行segue(具有添加的属性).我有点坚持如何实现这一点,因为我无法PerformSegue从子类中使用UICollectionViewSource,我似乎无法从中获取所选单元格UICollectionView.

这是我到目前为止的简略版本:

收集来源:

public class ProductCollectionDataSource : UICollectionViewSource
{       
    public ProductCollectionDataSource()
    {
        Products = new List<FeedItem>();
    }

    public List<FeedItem> Products { get; set; }

    public override void ItemUnhighlighted(UICollectionView collectionView, NSIndexPath indexPath)
    {
        var cell = (MultiColumnCell)collectionView.CellForItem(indexPath);
        cell.Alpha = 1.0f;
        // Perform segue here, passing this cell's data...?
    }
}
Run Code Online (Sandbox Code Playgroud)

UIViewController中:

public partial class DashboardViewController : UIViewController
{
    private ProductCollectionDataSource _dataSource;

    public override void ViewDidLoad()
    {
        _dataSource = new ProductCollectionDataSource();
        CollectionView.Source = _dataSource;

        GetProducts();
    }

    private async void GetProducts()
    {
        _dataSource.Products = new List<FeedItem>(await API.FeedService.Get());
        CollectionView.ReloadData();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么,如何根据UICollectionView中选定的单元格触发UIViewController中的segue?

pna*_*avk 6

您可以传入对控制器的引用,然后使用它来执行Segue:

public class ProductCollectionDataSource : UICollectionViewSource
{
        WeakReference<DashboardViewController>  _dvc;

        public List<FeedItem> Products { get; set; }

        public ProductCollectionDataSource(DashboardViewController parentVc)
        {
            Products = new List<FeedItem>();

            _dvcRef = new WeakReference<DashboardViewController>(parentVc);
        }

        public override void ItemUnhighlighted(UICollectionView collectionView, NSIndexPath indexPath)
        {
            var cell = (MultiColumnCell)collectionView.CellForItem(indexPath);

            cell.Alpha = 1.0f;

            if (_dvcRef.TryGetTarget(out DashboardViewController dashboardVc){
                dashboardVc.PerformSegue("Identifier"); 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


foO*_*oOg 6

  1. 在故事板中设置你的segue(拖放)
  2. 打开右侧面板添加一个segue标识符(基本上是一个像"CustomSegue"这样的字符串)
  3. 使用collectionView委托(didSelectItemAtIndexPath :)来触发用户点击单元格
  4. 调用[self performSegueWithIdentifier:@"CustomSegue"所有者:self]
  5. 在管理UICollectionVIew的控制器中实现方法prepareForSegue
  6. 检查[segue.identifier isEqualToString:@"CustomSegue"]
  7. 如果是这样,那么获取segue.destinationViewController(它应该是你的DetailViewController
  8. 传递你想要的任何属性(segue.destinationViewController.property = propertyIWantToPass)