Xcode Swift命令行工具从键盘读取1个字符,而没有回显或需要按回车键 [英] Xcode Swift Command Line Tool reads 1 char from keyboard without echo or need to press return

查看:151
本文介绍了Xcode Swift命令行工具从键盘读取1个字符,而没有回显或需要按回车键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective C或Swift中,我需要一个函数,例如旧的"getch()",以便从键盘上读取单个字符而没有回声,并且在键入字符以使函数继续运行后,没有nedd按下回车键

I need a function, like the old "getch()", in Objective C or Swift to read one single character from the keyboard without echo and without the nedd to press return after the character has been typed to make the function continue.

我知道,这仅在对命令行工具进行编程时才有趣,例如进行选择或编写编辑器.

This is, I know, only interesting when programming command line tools, perhaps to make a selection or write an editor.

推荐答案

下面是用Swift编写的与Swift一起使用的函数:

Here is the function for use with Swift, written in Swift:

func GetKeyPress () -> Int
{
    var key: Int = 0
    var c: cc_t = 0
    var cct = (c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c) // Set of 20 Special Characters
    var oldt: termios = termios(c_iflag: 0, c_oflag: 0, c_cflag: 0, c_lflag: 0, c_cc: cct, c_ispeed: 0, c_ospeed: 0)

    tcgetattr(STDIN_FILENO, &oldt) // 1473
    var newt = oldt
    newt.c_lflag = 1217  // Reset ICANON and Echo off
    tcsetattr( STDIN_FILENO, TCSANOW, &newt)
    key = Int(getchar())  // works like "getch()"
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt)
    return key
}

这篇关于Xcode Swift命令行工具从键盘读取1个字符,而没有回显或需要按回车键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆