NavigationController Hero转场动画无效果,跳转详情页如何实现动画?
问题核心
你的代码存在两个关键错误导致动画失效:
- 误用了
modalAnimationType属性,它仅适用于模态跳转(present/dismiss),而push跳转需要使用navigationAnimationType - 未给导航控制器启用Hero,也未给跳转前后的视图设置匹配的
heroID——Hero的push转场依赖视图ID匹配来识别动画元素
具体修复步骤
启用导航控制器的Hero功能
在SearchViewController的viewDidLoad中添加:navigationController?.hero.isEnabled = true也可以直接在Storyboard中选中NavigationController,在「Identity Inspector」的「User Defined Runtime Attributes」里添加
hero.isEnabled,类型设为Boolean,值为YES。替换正确的动画类型属性
将代码中的vc.hero.modalAnimationType替换为vc.hero.navigationAnimationType:vc.hero.navigationAnimationType = .zoomSlide(direction: .down)给跳转视图设置匹配的heroID
- 在SearchViewController的Cell配置代码中,给需要转场的视图(比如海报ImageView)设置ID:
// 假设cell内的海报视图为posterImageView cell.posterImageView.hero.id = "moviePoster_\(indexPath.row)" - 在DetailViewController的
viewDidLoad中,给对应的目标视图设置相同ID:// 需提前接收传入的行索引 detailPosterImageView.hero.id = "moviePoster_\(currentRowIndex)"
(如果仅需要控制器整体的push动画,可跳过此步,但设置ID能实现更精准的元素转场)
- 在SearchViewController的Cell配置代码中,给需要转场的视图(比如海报ImageView)设置ID:
确认Hero库集成正常
检查是否通过CocoaPods或Swift Package Manager正确导入Hero,且项目中无其他自定义转场逻辑干扰Hero的运行。
修复后的完整代码示例
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController let back = UIBarButtonItem() // 启用导航控制器的Hero navigationController?.hero.isEnabled = true // 设置push转场动画类型 vc.hero.navigationAnimationType = .zoomSlide(direction: .down) back.title = self.viewModel.moviesList?[indexPath.row].Title back.tintColor = .black navigationItem.backBarButtonItem = back vc.viewModel.movieId = self.viewModel.moviesList?[indexPath.row].imdbID // 传递行索引用于设置heroID vc.currentRowIndex = indexPath.row self.navigationController?.pushViewController(vc, animated: true) }
内容的提问来源于stack exchange,提问作者LordGrim
相关产品推荐
相关产品推荐

