如何在Swift Playground中实现按键触发UITextView显示数组随机字符串
Swift Playground 实现黑客模拟器(按键触发随机字符串显示)
嘿,这两个问题核心逻辑是相通的——就是要做类似黑客打字机的效果:在UITextView里,用户每按一次键盘,就显示数组里的随机字符串(或者逐字显示)。下面给你完整的实现方案:
一、基础UI搭建(创建UITextView)
首先,Swift Playground默认是代码环境,要显示UI得先配置一下。我们先创建一个视图控制器,把UITextView加进去,设置成黑客风格的样式:
import UIKit import GameplayKit // 因为要用GKRandomSource import PlaygroundSupport class HackerSimVC: UIViewController { // 用来展示内容的文本框 let outputTextView = UITextView() // 你的100个字符串数组,这里用示例数据代替,你可以替换成自己的 let hackContent = ["[SYSTEM BOOTING]", "CONNECTING TO SERVER...", "USER AUTH: SUCCESS", "LOADING ENCRYPTION KEYS...", "INTRUDER ALERT! BLOCKING IP...", "DOWNLOADING CONFIDENTIAL DATA...", "TRANSFER COMPLETE", "DISCONNECTING FROM MAINFRAME..."] // 随机数生成器,你已经在用这个啦 let randomGenerator = GKRandomSource.sharedRandom() // 新增两个属性,用来实现逐字打字效果(可选) var currentDisplayString = "" var currentCharIndex = 0 override func viewDidLoad() { super.viewDidLoad() setupTextViewStyle() setupKeyboardListener() } // 配置UITextView的样式和布局 private func setupTextViewStyle() { view.backgroundColor = .black outputTextView.frame = view.bounds // 黑客风样式 outputTextView.backgroundColor = .black outputTextView.textColor = .green outputTextView.font = UIFont.monospacedSystemFont(ofSize: 16, weight: .regular) outputTextView.isEditable = false // 禁止用户编辑,只用来展示 outputTextView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) view.addSubview(outputTextView) }
二、监听键盘按键
接下来要让程序能捕获用户的键盘输入,这里用UIKeyCommand来实现,它能让我们监听任意按键事件:
// 设置键盘监听 private func setupKeyboardListener() { // 创建一个监听任意按键的命令,空input表示匹配所有可打印按键 let anyKeyCommand = UIKeyCommand(input: "", modifierFlags: [], action: #selector(handleKeyPress)) // 添加到控制器,这样就能响应按键了 addKeyCommand(anyKeyCommand) // 如果想监听特殊按键(比如回车、方向键),可以再加对应的命令 let enterKeyCommand = UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(handleKeyPress)) addKeyCommand(enterKeyCommand) } // 处理按键事件的方法 @objc private func handleKeyPress() { // 两种模式可选,你可以选自己需要的: // 模式1:每次按键显示完整的随机字符串 // let randomText = hackContent[randomGenerator.nextInt(upperBound: hackContent.count)] // outputTextView.text.append("\(randomText)\n") // 模式2:逐字显示(更接近hackertyper的效果) if currentCharIndex >= currentDisplayString.count { // 当当前字符串显示完,取新的随机字符串 currentDisplayString = hackContent[randomGenerator.nextInt(upperBound: hackContent.count)] currentCharIndex = 0 outputTextView.text.append("\n") // 换行开始新内容 } // 取当前要显示的字符 let char = currentDisplayString[currentDisplayString.index(startIndex, offsetBy: currentCharIndex)] outputTextView.text.append(String(char)) currentCharIndex += 1 // 自动滚动到最新内容,避免用户看不到底部 let bottomRange = NSRange(location: outputTextView.text.count - 1, length: 1) outputTextView.scrollRangeToVisible(bottomRange) } } // 把控制器设置为Playground的实时视图,并且让Playground一直运行 PlaygroundPage.current.liveView = HackerSimVC() PlaygroundPage.current.needsIndefiniteExecution = true
三、关键细节说明
needsIndefiniteExecution:必须设置这个,否则Playground执行完代码就会停止,无法接收键盘输入。GKRandomSource:你已经在使用的随机数工具,nextInt(upperBound:)能保证不会越界访问数组,很安全。- 两种显示模式:我写了两种模式,模式1是每次按键显示完整字符串,模式2是逐字显示,更贴近hackertyper的效果,你可以注释掉其中一种用另一种。
- 自动滚动:每次添加内容后滚动到底部,用户不用手动拖动文本框,体验更好。
内容的提问来源于stack exchange,提问作者Harshita Arora
相关产品推荐
相关产品推荐

