首页 > 解决方案 > 通过单击自定义 UICollectionViewCell 中的按钮执行 segue

问题描述

我试图通过单击自定义 UICollectionViewCell 中的按钮来了解执行 segue 的正确方法是什么(我正在使用情节提要创建应用程序的屏幕)。

我有一个包含 UICollectionView 的视图控制器:

    MyDataSource myDataSource = new MyDataSource(listOfItems);
     
    myCollectionView.Source = myDataSource;

MyDataSource 是 UICollectionViewSource 的子类

     public override UICollectionViewCell GetCell(UICollectionView collectionView, Foundation.NSIndexPath indexPath)
     {
            MyCustomCell customListCell = (MyCustomCell)collectionView.DequeueReusableCell("listCell", indexPath);
            customListCell.updateItem(indexPath.Row);
            return customListCell;
     }

MyCustomCell updateItem 方法更新单元格的属性并为按钮连接 TouchUpInside 事件:

    public void updateItem(int index)
    { 
         myButton.TouchUpInside += (sender, e) =>
         {
            /* NOW I WANT TO PERFORM THE SEGUE 
               AND PASS THE INDEX THAT WAS CLICKED */
         };  
    }

在阅读了一些旧问题后,提出了一些解决方案,我试图避免:

  1. 传递对父 ViewController 的引用并使用此引用来执行 segue。

  2. 在情节提要中创建一个 segue,当用户单击按钮时,保存一个可以从下一个 ViewController 访问的静态值。

在我看来,这两种解决方案更像是一种解决方法,使用事件是正确的路径,但我不确定实施。

例如,我将在 MyCustomCell 中创建一个 EventHandler:

public event EventHandler<MyDataType> ButtonClicked;

然后在 TouchUpInside 中:

    myButton.TouchUpInside += (sender, e) =>
    {
             ButtonClicked(this, MyDataType);
    };

但是为了让它工作,我需要在父视图控制器中使用这个事件:

   MyCustomCell.ButtonClicked += (sender, e) =>
   {
                PerformSegue("theSegueIdentifier", this);
   };

我在父视图控制器中没有对 MyCustomCell 的任何引用,那么如何在父视图控制器中使用此事件?

标签: c#iosxamarinxamarin.ios

解决方案


这个怎么样:

风险投资:

MyDataSource myDataSource = new MyDataSource(listOfItems,CurrentVC);
</p>

数据源:

this.currentVC = CurrentVC;

myButton.TouchUpInside += (sender, e) =>
{

     currentVC.PerformSegue("theSegueIdentifier", this);
     //currentVC is the instance of current controller  
};

最好建议尝试这个导航,然后不需要为每个单元格创建与 Button 相关的 Segue:

NextViewController nextController = this.Storyboard.InstantiateViewController ("NextViewController") as NextViewController ;
if (nextController != null) {     
     this.NavigationController.PushViewController (nextController, true);
}

推荐阅读