1

Im trying to programm a text adventure. I have a NSTextView in which the user can write commands and get a response but I can't find a way to "pause" a function to wait for the users response.

import Cocoa

@IBOutlet var textView: NSTextView!

var playerName:String = ""
var enteredString:String = ""

//Keyboard Input

private func returnChar(theEvent: NSEvent) -> Character?{
    let s: String = theEvent.characters!
    for char in s{
        return char
    }
    return nil
}

override func keyUp (theEvent: NSEvent) {
    let s: String = String(self.returnChar(theEvent)!)
    enteredString.extend(s)

    if theEvent.keyCode == 36 {

        //Here I'd like to 
        //say that start() 
        //should continue

    }
}

//Story

func start() {
    textView.string?.extend("Hi, what's your name?\n")

    //Here I'd like to 
    //wait for the
    //users response

    playerName = enteredString
    textView.string?.extend("Are you sure that I should call you \(playerName)")

}

Thanks for your reply :D

4

3 回答 3

1

如果您使用的是 Swift 2,您可以使用 readLine() 等待用户在命令行中按下回车键。它返回字符串?因为用户可以在不输入任何内容的情况下按 Enter。

于 2015-07-31T13:03:15.733 回答
0

我建议等待输入NSTextView不是一个好策略。

如果您有一个知道您的应用程序处于什么状态的方法怎么办?然后,每当您获得要使用的文本时,将其发送到该方法并让它根据状态决定如何使用它(名称,命令......)。同时,您的应用程序刚刚返回到运行循环,让用户做他们想做的事。

于 2015-07-31T13:06:22.663 回答
0

添加 UITextField 委托和 UITextField 用于用户输入。将 UITextField 委托设置为 self 并添加方法:'textFieldShouldReturn'。

在此方法中,每当用户输入内容时处理逻辑。这是一个简短的片段:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    var userInputTextField: UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        userInputTextField = UITextField(frame: CGRectMake(0, 100, view.frame.width, 100))
        userInputTextField?.delegate = self
        userInputTextField?.returnKeyType = UIReturnKeyType.Done
        view.addSubview(userInputTextField!)
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        println(textField.text)
        return true
    }
}
于 2015-07-31T13:22:09.137 回答