我试图通过单击自定义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 */
};
}
在阅读了一些旧问题后,提出了一些解决方案,我试图避免:
将引用传递给父视图控制器,并使用此引用执行 segue。
在情节提要中创建 segue,当用户单击按钮时,保存可从下一个 ViewController 访问的所选内容的静态值。
在我看来,这两个解决方案更像是一种解决方法,使用 Events 是正确的路径,但我不确定实现。
例如,我将在 MyCustomCell 中创建一个 EventHandler:
public event EventHandler<MyDataType> ButtonClicked;
然后在TouchUpInside中:
myButton.TouchUpInside += (sender, e) =>
{
ButtonClicked(this, MyDataType);
};
但是要使其正常工作,我需要在父视图控制器中使用此事件:
MyCustomCell.ButtonClicked += (sender, e) =>
{
PerformSegue("theSegueIdentifier", this);
};
我在父视图控制器中没有任何对 MyCustomCell 的引用, 那么如何在父视图控制器中使用此事件呢?
这个怎么样:
风投:
MyDataSource myDataSource = new MyDataSource(listOfItems,CurrentVC);
数据来源:
this.currentVC = CurrentVC;
myButton.TouchUpInside += (sender, e) =>
{
currentVC.PerformSegue("theSegueIdentifier", this);
//currentVC is the instance of current controller
};
更好的建议尝试这个导航,然后不需要创建Segue 与每个单元格的按钮相关:
NextViewController nextController = this.Storyboard.InstantiateViewController ("NextViewController") as NextViewController ;
if (nextController != null) {
this.NavigationController.PushViewController (nextController, true);
}
您可以在数据源类"MyDataSource"中添加另一个事件处理程序"buttonClicked2",并执行以下操作:
MyCustomCell.ButtonClicked += (sender, e) =>
{
//PerformSegue("theSegueIdentifier", this);
//instead of perform segue, you raise the event
buttonClicked2();
};
然后你可以填写其余的。