我试图了解通过单击自定义 UICollectionViewCell 中的按钮来执行转场的正确方法是什么(我正在使用 Storyboard来创建应用程序的屏幕)。
我有一个包含 UICollectionView 的 View Controller :
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 */
};
}
阅读了一些旧问题后,提出了一些解决方案,我试图避免:
将引用传递给父 ViewController 并使用此引用来执行转场。
在 Storyboard中创建一个 segue,当用户单击按钮时,保存选择的静态值,可以从下一个 ViewController 访问该值。
在我看来,这两个解决方案更多的是一种解决方法,并且使用事件是正确的路径,但我不确定具体的实现。
例如,我将在 MyCustomCell 中创建一个 EventHandler:
public event EventHandler<MyDataType> ButtonClicked;
然后在 TouchUpInside 中:
myButton.TouchUpInside += (sender, e) =>
{
ButtonClicked(this, MyDataType);
};
但是为了使其工作,我需要在父 View Controller 中使用此事件:
MyCustomCell.ButtonClicked += (sender, e) =>
{
PerformSegue("theSegueIdentifier", this);
};
我在父 View Controller 中没有任何对 MyCustomCell 的引用, 那么如何在父 View Controller 中使用此事件呢?
最佳答案
这个怎么样:
风险投资:
MyDataSource myDataSource = new MyDataSource(listOfItems,CurrentVC);
数据源:
this.currentVC = CurrentVC;
myButton.TouchUpInside += (sender, e) =>
{
currentVC.PerformSegue("theSegueIdentifier", this);
//currentVC is the instance of current controller
};
更好推荐尝试this导航,然后不需要创建Segue 与每个单元格的按钮相关:
NextViewController nextController = this.Storyboard.InstantiateViewController ("NextViewController") as NextViewController ;
if (nextController != null) {
this.NavigationController.PushViewController (nextController, true);
}
关于c# - 通过单击自定义 UICollectionViewCell 中的按钮来执行 segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181670/