gpt4 book ai didi

ios - 使用 prepareForSegue 将 Cell 数据发送到 destinationViewController

转载 作者:行者123 更新时间:2023-11-29 01:45:04 27 4
gpt4 key购买 nike

我已将 UILongPressGestureRecognizer 添加到我的 UICollectionViewCell 并创建了一个转场,因此通过长按一个 cell 用户转场到一个 View Controller

我已经有一个普通的 segue 使用 didSelect 方法显示单元格详细信息,但是辅助长按手势 segue 会将用户带到操作屏幕以删除单元格。

不幸的是,当使用 prepareForSegue 将单元格数据发送到 destinationViewController 时,我无法使用标准的 let indexPaths = self.collectionView.indexPathForSelectedRow() 方法,因为我在使用手势识别器时正在创建自己的选择。

那么如何使用 gestureRecognizer 将单元格数据发送到 destinationViewControllerprepareForSegue

if segue.identifier == "cellAction" {
let vc = segue.destinationViewController as! CellActionViewController

//This will cause an 'array index out of range error
let indexPaths = self.collectionView.indexPathsForSelectedItems()
let indexPath = indexPaths[0] as! NSIndexPath

//Here is how I would send the cell data
let selectedCell = Items[indexPath.row]

vc.selectedItem = selectedCell
}

最佳答案

因此您需要访问被按下的特定单元格,并使用此信息从 prepareForSegue(_:sender:) 中获取其索引路径。

首先要注意的是 prepareForSegue 方法中的 sender 参数。我假设您正在从手势处理函数调用 performSegueWithIdentifier(_:sender:) 。请注意,它还有一个 sender 参数,它与传递给 prepareForSegue 的对象相同。您可以使用它来传递您的单元实例。

要注意的第二件事是 UIGestureRecognizer 有一个 view 属性,它很可能是单元格本身。有了这些知识,您就可以将按下的单元格实例传递给 prepareForSegue:

func handleLongPress(longPress: UILongPressGestureRecognizer) {
if longPress.state == .Ended {
performSegueWithIdentifier("cellAction", sender: longPress.view)
}
}

现在,在 prepareForSegue 中,您可以将 sender 转换为您的单元类,并使用 UICollectionViewindexPathForCell( _:) 方法:

override prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "cellAction" {
let vc = segue.destinationViewController as! CellActionViewController
if let cell = sender as? MyCell {
let indexPath = collectionView.indexPathForCell(cell)
let selectedItem = items[indexPath.row]
vc.selectedItem = selectedItem
} else {
fatalError("Invalid sender, was expecting instance of MyCell.)
}
}
}

关于ios - 使用 prepareForSegue 将 Cell 数据发送到 destinationViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32020339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com