如何在xcode 9.2中的playground项目中使用swift从用户那里获得输入

问题描述 投票:0回答:1

这是在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
ios swift
1个回答
0
投票

你不能在快速的操场上使用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/

© www.soinside.com 2019 - 2024. All rights reserved.