You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中iOS设置风格侧滑返回手势实现方案咨询

实现首页到计算器页面的设置式转场及左滑返回方案

需求说明

从首页Home ViewController点击“happy number Rechner”按钮跳转至计算器ViewController,转场效果与iOS设置应用一致(即导航控制器的push动画),同时支持左滑手势返回首页。


实现步骤

一、Storyboard 可视化配置

  1. 给首页Home ViewController嵌入UINavigationController:选中首页控制器,在Xcode菜单栏选择 Editor > Embed In > Navigation Controller,这是实现设置式转场和左滑返回的基础。
  2. 设置转场关联:按住首页的“happy number Rechner”按钮,拖线到计算器ViewController,在弹出的菜单中选择 Show(Push),完成Storyboard层面的跳转配置。
  3. 可选:给计算器ViewController设置Storyboard ID(如CalculatorVC),方便后续代码跳转(如果不用拖线方式的话)。

二、代码层面补充(按需选择)

1. 代码方式实现跳转(替代Storyboard拖线)

如果需要用代码控制跳转,在首页Home ViewController中添加按钮点击事件:

@IBAction func openCalculator(_ sender: UIButton) {
    guard let calculatorVC = storyboard?.instantiateViewController(withIdentifier: "CalculatorVC") as? ViewController else {
        return
    }
    navigationController?.pushViewController(calculatorVC, animated: true)
}

注意:需提前在Storyboard中给计算器控制器设置对应的Storyboard ID

2. 确保左滑返回手势正常工作

导航控制器默认自带左滑返回手势,但如果页面有自定义导航栏或手势失效,可在计算器ViewController的viewDidLoad中添加:

override func viewDidLoad() {
    super.viewDidLoad()
    // 修复手势失效问题
    navigationController?.interactivePopGestureRecognizer?.delegate = nil
    // 保留你原有的代码
    buttons.backgroundColor = .gray
}

三、原计算器代码优化建议

你提供的代码存在两处冗余问题,建议修正:

  1. 删除happycheck方法内重复定义的happyFunc和happyChecker函数,直接复用类内已定义的方法即可,避免代码冗余。
  2. 将全局的alert移至happycheck方法内创建,避免重复添加Action导致弹窗多次显示,修正后代码如下:
@IBAction func happycheck(_ sender: UIButton) {
    guard let inputText = calculatorLabel.text, let inputNumber = Int(inputText), inputNumber <= 9999999999999999 else {
        let alert = UIAlertController(title: "Warning", message: "Your number is too big.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
            print("OK tap")
        }))
        present(alert, animated: true)
        return
    }
    number = inputNumber
    happyChecker(inputNumber)
}

内容的提问来源于stack exchange,提问作者juliusderG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:50:23