Swift如何实现自定义CollectionViewCell到xib的Segue/代码跳转
场景适配实现方案
首先明确前提:原生Storyboard Segue要求源和目标控制器至少有一个绑定在当前Storyboard画布上,你当前PlayerViewController是独立xib实现,可根据是否愿意调整Storyboard结构选以下两种方案:
方案一:Storyboard无控件连线配置Segue
该方案不需要给CollectionViewCell或其他UI组件拖线,仅需要在Storyboard内完成控制器层级的Segue绑定即可:
- 打开主Storyboard画布,从右侧组件库拖入一个空白ViewController场景,在身份检查器面板把它的Class设置为
PlayerViewController,同时在Nib Name栏填写你现有PlayerViewController对应的xib文件名,系统会自动加载你xib里写好的布局,不需要重复搭UI。 - 选中主ViewController(即承载CollectionView的那个控制器),按住Control键从主VC的图标栏拖线到刚添加的PlayerVC场景,选择你需要的跳转类型(模态弹出/导航栈Push都可),此时生成的Segue是绑定在两个控制器之间的,和任何具体UI控件无关,不需要拖拽关联cell。
- 选中这条Segue连接线,在属性检查器的Identifier栏填入自定义的标识符,比如
ShowPlayer,Segue配置就完成了。 - 传参与跳转触发逻辑:
- 在主ViewController中加一个临时存储属性:
var selectedVideo: Video? - 实现CollectionView的点击代理方法,拿到点击对应的Video模型后触发Segue:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedVideo = videoDataArray[indexPath.item] performSegue(withIdentifier: "ShowPlayer", sender: nil) }- 重写跳转准备方法完成参数传递:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "ShowPlayer", let playerVC = segue.destination as? PlayerViewController else { return } playerVC.currentVideo = selectedVideo } - 在主ViewController中加一个临时存储属性:
方案二:纯代码自定义Segue(完全不需要操作Storyboard连线)
如果你不想改动现有xib结构、不想往主Storyboard里加额外场景,可以直接通过自定义Segue类实现,标识符直接在代码里定义,不需要Storyboard配置:
- 新建一个继承
UIStoryboardSegue的自定义类,在内部定义静态标识符、重写跳转执行逻辑:
class PlayerPresentSegue: UIStoryboardSegue { static let id = "PlayerPresentSegue" override func perform() { // 跳转逻辑根据你的导航结构改,这里示例模态弹出 source.present(destination, animated: true) } }
- 在CollectionView的点击代理方法里,初始化xib对应的PlayerViewController、传入Video模型,手动初始化Segue并执行即可:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let targetVideo = videoDataArray[indexPath.item] guard let playerVC = PlayerViewController(nibName: "PlayerViewController", bundle: nil) as? PlayerViewController else { return } playerVC.currentVideo = targetVideo let segue = PlayerPresentSegue(identifier: PlayerPresentSegue.id, source: self, destination: playerVC) segue.perform() }
踩坑提示:不要尝试给纯代码注册的CollectionViewCell直接绑定Segue,Cell复用机制会导致跳转逻辑触发异常,绑定在控制器层级的Segue、纯代码触发的Segue稳定性更高。
内容的提问来源于stack exchange,提问作者V777
相关产品推荐
相关产品推荐

