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

Swift Playground时间线视图添加链接及页面跳转问题咨询

我来帮你解决这两个问题,这在Swift Playground里其实有明确的实现方式,咱们一步步来:

一、让时间线显示标记/链接的正确姿势

你遇到时间线不显示链接的问题,大概率是注释格式不对——Swift Playground对可渲染的Markdown注释有专属要求:

  • 必须用正确的注释前缀:只有以//:开头的单行注释,或者用/*: ... */包裹的多行注释,才会被Playground解析成富文本显示在时间线里。普通的//注释只会作为代码注释,不会渲染成带链接的内容。
  • 链接格式要准确:
    • 跳转到上/下一页:用[链接文本](@next)或者[链接文本](@previous)
    • 跳转到指定页面:用[链接文本](页面文件名),这里的“页面文件名”必须和你Playground里的.playgroundpage文件名称完全一致(不需要带后缀)。
  • 小提示:写完注释后记得运行一下Playground,有时候时间线需要重新渲染才会显示出链接。

举个实际可用的代码示例:

//: 🚀 点击这里直接跳转到下一页 [前往下一页](@next)

//: 📚 或者跳转到指定的【字符串操作】页面 [字符串操作](字符串操作)
二、通过按钮点击跳转到其他Playground页面

如果想要用交互式按钮实现跳转,需要借助PlaygroundSupport框架来操作页面导航,具体实现步骤如下:

  1. 导入必要的框架:import UIKit和import PlaygroundSupport
  2. 创建自定义视图控制器,在里面添加按钮并绑定点击事件
  3. 在点击事件里调用PlaygroundPage.current.navigateTo(page:)方法完成跳转

完整代码示例:

import UIKit
import PlaygroundSupport

class NavigationViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground
        
        // 创建跳转到下一页的按钮
        let nextPageButton = UIButton(type: .roundedRect)
        nextPageButton.setTitle("点击跳转到下一页", for: .normal)
        nextPageButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        nextPageButton.frame = CGRect(x: 80, y: 300, width: 250, height: 50)
        nextPageButton.addTarget(self, action: #selector(navigateToNextPage), for: .touchUpInside)
        view.addSubview(nextPageButton)
        
        // 创建跳转到指定页面的按钮
        let targetPageButton = UIButton(type: .roundedRect)
        targetPageButton.setTitle("跳转到【数组教程】页面", for: .normal)
        targetPageButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        targetPageButton.frame = CGRect(x: 80, y: 380, width: 250, height: 50)
        targetPageButton.addTarget(self, action: #selector(navigateToTargetPage), for: .touchUpInside)
        view.addSubview(targetPageButton)
    }
    
    // 跳转到下一页的逻辑
    @objc private func navigateToNextPage() {
        guard let nextPage = PlaygroundPage.current.next else {
            print("没有下一页啦")
            return
        }
        PlaygroundPage.current.navigateTo(page: nextPage)
    }
    
    // 跳转到指定名称页面的逻辑
    @objc private func navigateToTargetPage() {
        guard let parent = PlaygroundPage.current.parent,
              let targetPage = parent.pageNamed("数组教程") else {
            print("找不到指定页面哦")
            return
        }
        PlaygroundPage.current.navigateTo(page: targetPage)
    }
}

// 设置当前页面的liveView为我们的导航控制器
PlaygroundPage.current.liveView = NavigationViewController()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:25:20