如何实现延迟跳转?两个ViewController间5秒自动跳转实现咨询
实现LemonVC 5秒后自动跳转到SecondVC
没问题,我来帮你完成这个自动跳转的功能!你已经搭好了DispatchQueue.main.asyncAfter的框架,只需要在闭包里补全跳转逻辑就可以了。下面分两种常见的页面跳转场景给你完整代码:
场景1:LemonVC嵌入在导航控制器中(使用Push跳转)
如果你的页面是基于导航栈结构的,用pushViewController来跳转最适配:
class LemonVC: UIViewController { @IBOutlet weak var LemonGif: UIImageView! override func viewDidLoad() { super.viewDidLoad() LemonGif.loadGif(name: "sufoo") // 5秒后执行跳转(把你原来的4秒改成了5秒,贴合你的需求) DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) { [weak self] in // 1. 从Storyboard获取SecondVC(假设你的主Storyboard是Main.storyboard,且SecondVC的Storyboard ID设为"SecondVC") guard let secondVC = self?.storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC else { print("无法获取SecondVC,请检查Storyboard ID是否设置正确") return } // 2. 执行Push跳转 self?.navigationController?.pushViewController(secondVC, animated: true) } } }
场景2:使用模态方式跳转(Present)
如果不需要导航栈,直接弹出SecondVC的话,用present方法更合适:
class LemonVC: UIViewController { @IBOutlet weak var LemonGif: UIImageView! override func viewDidLoad() { super.viewDidLoad() LemonGif.loadGif(name: "sufoo") DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) { [weak self] in guard let secondVC = self?.storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondVC else { print("无法获取SecondVC,请检查Storyboard ID是否设置正确") return } // 设置模态跳转的展示样式,这里用全屏示例,可根据需求调整 secondVC.modalPresentationStyle = .fullScreen // 执行模态跳转 self?.present(secondVC, animated: true) } } }
关键注意点:
- 一定要给
SecondVC在Storyboard里设置正确的Storyboard ID,要和代码里的字符串完全匹配 - 用
[weak self]是为了避免循环引用,防止内存泄漏 - 如果你的
SecondVC是纯代码创建的,把获取VC的代码换成let secondVC = SecondVC()即可
内容的提问来源于stack exchange,提问作者JIN
相关产品推荐
相关产品推荐

