gpt4 book ai didi

ios - 如何在 xcode 9.2 的 Playground 项目中使用 swift 获取用户输入

转载 作者:行者123 更新时间:2023-11-30 11:44:09 28 4
gpt4 key购买 nike

这在 ios11 上出现错误,知道吗!?

来自主题:如何在 xcode 8.2 的 Playground 项目中使用 swift 获取用户的输入

import UIKit
import PlaygroundSupport
// new code user input

class V: UIViewController {
var textField = UITextField(frame: CGRect(x: 20, y: 20, width: 200, height: 24))
override func viewDidLoad() {
super.viewDidLoad()
//view.addSubview(textField)
textField.backgroundColor = .white
textField.delegate = self
}
}
extension V: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Do stuff here
print("Please enter your name")
var name = readLine()
print("name: \(name!)")
return true
}
}
let v = V()
v.view.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
PlaygroundPage.current.liveView = v.view
PlaygroundPage.current.needsIndefiniteExecution = true

最佳答案

您不能在 Swift Playground 中使用 readline()。为此,您必须使用命令行工具。

而且你的代码只显示黑色;)..我修改了它,所以你可以看到一个文本字段:

import UIKit
import PlaygroundSupport
// new code user input

class V: UIViewController {
var textField: UITextField!
override func loadView() {
//super.viewDidLoad()
//view.addSubview(textField)

let view = UIView()
view.backgroundColor = .white

textField = UITextField()
textField.backgroundColor = .white
textField.delegate = self
textField.borderStyle = .roundedRect

view.addSubview(textField)

textField.text = "Hello world!"

// Layout

textField.translatesAutoresizingMaskIntoConstraints = false
let margins = view.layoutMarginsGuide
NSLayoutConstraint.activate([
textField.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20),
textField.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
textField.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
])

self.view = view
}
}
extension V: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Do stuff here
print("Please enter your name")
var name = readLine()
print("name: \(name!)")
return true
}
}
let v = V()
//v.view.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
PlaygroundPage.current.liveView = v
//PlaygroundPage.current.needsIndefiniteExecution = true

可以在这里找到一个很好且更完整的示例:https://www.ralfebert.de/ios-examples/uikit/uicatalog-playground/UITextField/

关于ios - 如何在 xcode 9.2 的 Playground 项目中使用 swift 获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027958/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com