当前位置: 首页 > news >正文

Unity 如何在 iOS 新增键盘 KeyCode 响应事件

1.定位到文件UnityView+Keyboard.mm同如下路径:

2.打开该Objective-C脚本进行编辑,找到关键函数: createKeyboard:

- (void)createKeyboard
{// only English keyboard layout is supportedNSString* baseLayout = @"1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm,./!@#$%^&*()_+{}:\"|<>?~ \t\r\b\\";NSString* numpadLayout = @"1234567890-=*+/.\r";NSString* upperCaseLetters = @"QWERTYUIOPASDFGHJKLZXCVBNM";size_t sizeOfKeyboardCommands = baseLayout.length + numpadLayout.length + upperCaseLetters.length + 11;NSMutableArray* commands = [NSMutableArray arrayWithCapacity: sizeOfKeyboardCommands];void (^addKey)(NSString *keyName, UIKeyModifierFlags modifierFlags) = ^(NSString *keyName, UIKeyModifierFlags modifierFlags){UIKeyCommand* command = [UIKeyCommand keyCommandWithInput: keyName modifierFlags: modifierFlags action: @selector(handleCommand:)];
#if UNITY_HAS_IOSSDK_15_0if (@available(iOS 15.0, tvOS 15.0, *))command.wantsPriorityOverSystemBehavior = YES;
#endif[commands addObject:command];};for (NSInteger i = 0; i < baseLayout.length; ++i){NSString* input = [baseLayout substringWithRange: NSMakeRange(i, 1)];NSLog(@"%@ !!!",input);addKey(input, kNilOptions);}for (NSInteger i = 0; i < numpadLayout.length; ++i){NSString* input = [numpadLayout substringWithRange: NSMakeRange(i, 1)];addKey(input, UIKeyModifierNumericPad);}for (NSInteger i = 0; i < upperCaseLetters.length; ++i){NSString* input = [upperCaseLetters substringWithRange: NSMakeRange(i, 1)];addKey(input, UIKeyModifierShift);}// pageUp, pageDownaddKey(@"UIKeyInputPageUp", kNilOptions);addKey(@"UIKeyInputPageDown", kNilOptions);// up, down, left, right, escaddKey(UIKeyInputUpArrow, kNilOptions);addKey(UIKeyInputDownArrow, kNilOptions);addKey(UIKeyInputLeftArrow, kNilOptions);addKey(UIKeyInputRightArrow, kNilOptions);addKey(UIKeyInputEscape, kNilOptions);// caps Lock, shift, control, option, commandaddKey(@"", UIKeyModifierAlphaShift);addKey(@"", UIKeyModifierShift);addKey(@"", UIKeyModifierControl);addKey(@"", UIKeyModifierAlternate);addKey(@"", UIKeyModifierCommand);keyboardCommands = commands.copy;
}

此函数由Unity定义,通过addKey函数负责初始化注册所有需要响应的按键.

   void (^addKey)(NSString *keyName, UIKeyModifierFlags modifierFlags) = ^(NSString *keyName, UIKeyModifierFlags modifierFlags){UIKeyCommand* command = [UIKeyCommand keyCommandWithInput: keyName modifierFlags: modifierFlags action: @selector(handleCommand:)];
#if UNITY_HAS_IOSSDK_15_0if (@available(iOS 15.0, tvOS 15.0, *))command.wantsPriorityOverSystemBehavior = YES;
#endif[commands addObject:command];};

函数接受两个参数第一个是keyName表示接收的按键名称例如键盘上的a-z,第二个参数为UIKeyModifierFlags表示作为Modifier的按键种类如下:

  typedef   NS_OPTIONS(NSInteger, UIKeyModifierFlags) {UIKeyModifierAlphaShift     = 1 << 16,  // This bit indicates CapsLockUIKeyModifierShift          = 1 << 17,UIKeyModifierControl        = 1 << 18,UIKeyModifierAlternate      = 1 << 19,UIKeyModifierCommand        = 1 << 20,UIKeyModifierNumericPad     = 1 << 21,} API_AVAILABLE(ios(7.0));

使用时例如用户需要接收处理command a,需调用addKey(@"a", UIKeyModifierCommand); 针对于特殊按键对应的NSString存储于UIResponder.h中:

// These are pre-defined constants for use with the input property of UIKeyCommand objects.
UIKIT_EXTERN NSString *const UIKeyInputUpArrow         API_AVAILABLE(ios(7.0));
UIKIT_EXTERN NSString *const UIKeyInputDownArrow       API_AVAILABLE(ios(7.0));
UIKIT_EXTERN NSString *const UIKeyInputLeftArrow       API_AVAILABLE(ios(7.0));
UIKIT_EXTERN NSString *const UIKeyInputRightArrow      API_AVAILABLE(ios(7.0));
UIKIT_EXTERN NSString *const UIKeyInputEscape          API_AVAILABLE(ios(7.0));
UIKIT_EXTERN NSString *const UIKeyInputPageUp          API_AVAILABLE(ios(8.0));
UIKIT_EXTERN NSString *const UIKeyInputPageDown        API_AVAILABLE(ios(8.0));
UIKIT_EXTERN NSString *const UIKeyInputHome            API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputEnd             API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF1              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF1              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF2              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF3              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF4              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF5              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF6              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF7              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF8              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF9              API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF10             API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF11             API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputF12             API_AVAILABLE(ios(13.4), tvos(13.4)) API_UNAVAILABLE(watchos);
UIKIT_EXTERN NSString *const UIKeyInputDelete          API_AVAILABLE(ios(15.0), tvos(15.0)) API_UNAVAILABLE(watchos);

此文档以F1-F12按键添加为例:使用addKey(UIKeyInputF4, kNilOptions);

    addKey(UIKeyInputF1, kNilOptions);addKey(UIKeyInputF2, kNilOptions);addKey(UIKeyInputF3, kNilOptions);addKey(UIKeyInputF4, kNilOptions);
  1. 注册好按键后还需要在handleCommand函数中进行响应处理:

- (void)handleCommand:(UIKeyCommand *)command
{NSString* input = command.input;UIKeyModifierFlags modifierFlags = command.modifierFlags;char inputChar = ([input length] > 0) ? [input characterAtIndex: 0] : 0;int code = (int)inputChar; // ASCII codeUnitySendKeyboardCommand(command);if (![self isValidCodeForButton: code]){code = 0;}if ((modifierFlags & UIKeyModifierAlphaShift) != 0)code = UnityStringToKey("caps lock");if ((modifierFlags & UIKeyModifierShift) != 0)code = UnityStringToKey("left shift");if ((modifierFlags & UIKeyModifierControl) != 0)code = UnityStringToKey("left ctrl");if ((modifierFlags & UIKeyModifierAlternate) != 0)code = UnityStringToKey("left alt");if ((modifierFlags & UIKeyModifierCommand) != 0)code = UnityStringToKey("left cmd");if ((modifierFlags & UIKeyModifierNumericPad) != 0){switch (inputChar){case '0':code = UnityStringToKey("[0]");break;case '1':code = UnityStringToKey("[1]");break;case '2':code = UnityStringToKey("[2]");break;case '3':code = UnityStringToKey("[3]");break;case '4':code = UnityStringToKey("[4]");break;case '5':code = UnityStringToKey("[5]");break;case '6':code = UnityStringToKey("[6]");break;case '7':code = UnityStringToKey("[7]");break;case '8':code = UnityStringToKey("[8]");break;case '9':code = UnityStringToKey("[9]");break;case '-':code = UnityStringToKey("[-]");break;case '=':code = UnityStringToKey("equals");break;case '*':code = UnityStringToKey("[*]");break;case '+':code = UnityStringToKey("[+]");break;case '/':code = UnityStringToKey("[/]");break;case '.':code = UnityStringToKey("[.]");break;case '\r':code = UnityStringToKey("enter");break;default:break;}}if (input == UIKeyInputUpArrow)code = UnityStringToKey("up");else if (input == UIKeyInputDownArrow)code = UnityStringToKey("down");else if (input == UIKeyInputRightArrow)code = UnityStringToKey("right");else if (input == UIKeyInputLeftArrow)code = UnityStringToKey("left");else if (input == UIKeyInputEscape)code = UnityStringToKey("escape");else if ([input isEqualToString: @"UIKeyInputPageUp"])code = UnityStringToKey("page up");else if ([input isEqualToString: @"UIKeyInputPageDown"])code = UnityStringToKey("page down");KeyMap::iterator item = GetKeyMap().find(code);if (item == GetKeyMap().end()){// New key is down, register it and its timeUnitySetKeyboardKeyState(code, true);GetKeyMap()[code] = GetTimeInSeconds();}else{// Still holding the key, update its timeitem->second = GetTimeInSeconds();}
}

函数中input表示createKeyboard函数注册对应的keyName,modifierFlags表示注册时传入的modifierFlags.函数中的Code对应Unity的KeyCodeEnum:

using System;namespace UnityEngine
{// Key codes returned by Event.keyCode. These map directly to a physical key on the keyboard.public enum KeyCode{// Not assigned (never returned as the result of a keystroke)None = 0,// The backspace keyBackspace       = 8,// The forward delete keyDelete      = 127,// The tab keyTab     = 9,// The Clear keyClear       = 12,// Return keyReturn      = 13,// Pause on PC machinesPause       = 19,// Escape keyEscape      = 27,// Space keySpace       = 32,// Numeric keypad 0Keypad0     = 256,// Numeric keypad 1Keypad1     = 257,

前添加判断并给code进行赋值即可,F1-F12对应282-294以此为例代码如下:

   if (input == UIKeyInputF1)code = 282;else if (input == UIKeyInputF2)code = 283;else if (input == UIKeyInputF3)code = 284;
 
  1. 测试结果如下:

相关文章:

Unity 如何在 iOS 新增键盘 KeyCode 响应事件

1.定位到文件UnityViewKeyboard.mm同如下路径: 2.打开该Objective-C脚本进行编辑,找到关键函数: createKeyboard: - (void)createKeyboard {// only English keyboard layout is supportedNSString* baseLayout "1234567890-qwertyuiop[]asdfghjkl;\\zxcvbnm,./!#$%^&am…...

pytorh学习笔记——波士顿房价预测

机器学习的“hello world”&#xff1a;波士顿房价预测 波士顿房价预测的背景不用提了&#xff0c;简单了解一下数据集的结构。 波士顿房价的数据集&#xff0c;共有506组数据&#xff0c;每组数据共14项&#xff0c;前13项是影响房价的各种因素&#xff0c;比如&…...

让AI像人一样思考和使用工具,reAct机制详解

reAct机制详解 reAct是什么reAct的关键要素reAct的思维过程reAct的代码实现查看效果引入依赖&#xff0c;定义模型定义相关工具集合工具创建代理启动测试完整代码 思考 reAct是什么 reAct的核心思想是将**推理&#xff08;Reasoning&#xff09;和行动&#xff08;Acting&…...

Linux系列-常见的指令(二)

&#x1f308;个人主页&#xff1a; 羽晨同学 &#x1f4ab;个人格言:“成为自己未来的主人~” mv 剪切文件&#xff0c;目录 重命名 比如说&#xff0c;我们在最开始创建一个新的文件hello.txt 然后我们将这个文件改一个名字&#xff0c;改成world.txt 所以&#xff0c;…...

Leecode刷题之路第17天之电话号码的字母组合

题目出处 17-电话号码的字母组合-题目出处 题目描述 个人解法 思路&#xff1a; todo 代码示例&#xff1a;&#xff08;Java&#xff09; todo复杂度分析 todo 官方解法 17-电话号码的字母组合-官方解法 方法1&#xff1a;回溯 思路&#xff1a; 代码示例&#xff1a;&a…...

2023牛客暑期多校训练营3(题解)

今天下午也是小小的做了一下&#xff0c;OI&#xff0c;也是感觉手感火热啊&#xff0c;之前无意间看到的那个哥德巴赫定理今天就用到了&#xff0c;我以为根本用不到的&#xff0c;当时也只是感兴趣看了一眼&#xff0c;还是比较激动啊 话不多说&#xff0c;直接开始看题 Wo…...

Magnum IO

NVIDIA Magnum IO 文章目录 前言加速数据中心 IO 性能,随时随地助力 AINVIDIA Magnum IO 优化堆栈1. 存储 IO2. 网络 IO3. 网内计算4. IO 管理跨数据中心应用加速 IO1. 数据分析Magnum IO 库和数据分析工具2. 高性能计算Magnum IO 库和 HPC 应用3. 深度学习Magnum IO 库和深度…...

Flink job的提交流程

在Flink中&#xff0c;作业&#xff08;Job&#xff09;的提交流程是一个复杂的过程&#xff0c;涉及多个组件和模块&#xff0c;包括作业的编译、优化、序列化、任务分发、任务调度、资源分配等。Flink通过分布式架构来管理作业的生命周期&#xff0c;确保作业在不同节点上以高…...

git操作pull的时候出现冲突怎么解决

问&#xff1a; PS C:\Users\fury_123\Desktop\consumptionforecast> git branch * dev main PS C:\Users\fury_123\Desktop\consumptionforecast> git add . PS C:\Users\fury_123\Desktop\consumptionforecast> git commit -m 修改部分样式 [dev 74693e0] 修改部分样…...

Sentinel 1.80(CVE-2021-44139)

Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件&#xff0c;主要以流量为切入点&#xff0c;从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性 Report a Sentinel Security Vulnerability …...

黑马程序员C++提高编程学习笔记

黑马程序员C提高编程 提高阶段主要针对泛型编程和STL技术 文章目录 黑马程序员C提高编程一、模板1.1 函数模板1.1.1 函数模板基础知识 案例一&#xff1a; 数组排序1.2.1 普通函数与函数模板1.2.2 函数模板的局限性 1.2 类模板1.2.1 类模板的基础知识1.2.2 类模板与函数模板1.…...

力扣第1题:两数之和(图解版)

Golang版本 func twoSum(nums []int, target int) []int {m : make(map[int]int)for i : range nums {if _, ok : m[target - nums[i]]; ok {return []int{i, m[target - nums[i]]}} m[nums[i]] i}return nil }...

aws(学习笔记第三课) AWS CloudFormation

aws(学习笔记第三课) 使用AWS CloudFormation 学习内容&#xff1a; AWS CloudFormation的模板解析使用AWS CloudFormation启动ec2 server 1. AWS CloudFormation 的模版解析 CloudFormation模板结构 CloudFormation是AWS的配置管理工具&#xff0c;属于Infrastructure as Co…...

浅学React和JSX

往期推荐 一文搞懂大数据流式计算引擎Flink【万字详解&#xff0c;史上最全】-CSDN博客 数仓架构&#xff1a;离线数仓、实时数仓Lambda和Kappa、湖仓一体数据湖-CSDN博客 一文入门大数据准流式计算引擎Spark【万字详解&#xff0c;全网最新】_大数据 spark-CSDN博客 浅谈维度建…...

React 为什么 “虚拟 DOM 顶部有很多 provider“?

1、介绍React中的Context Provider 在 React 中&#xff0c;虚拟 DOM&#xff08;Virtual DOM&#xff09;是 React 用来高效更新 UI 的核心机制&#xff0c;它通过对比前后两次虚拟 DOM 树&#xff0c;确定哪些部分需要更新&#xff0c;以减少直接操作真实 DOM 的开销。而 “…...

忘记了 MySQL 8.0 的 root 密码,应该怎么办?

如果你忘记了 MySQL 8.0 的 root 密码&#xff0c;可以通过以下步骤来重置密码。请注意&#xff0c;这些步骤需要你有对 MySQL 服务器的物理或命令行访问权限。 步骤 1: 停止 MySQL 服务 首先&#xff0c;你需要停止正在运行的 MySQL 服务。你可以使用以下命令来停止 MySQL 服…...

Promise.reject()

Promise.reject() 静态方法返回一个已拒绝&#xff08;rejected&#xff09;的 Promise 对象&#xff0c;拒绝原因为给定的参数。 语法 Promise.reject(reason)参数 reason 该 Promise 对象被拒绝的原因。 返回值 返回一个已拒绝&#xff08;rejected&#xff09;的 Promi…...

大数据-163 Apache Kylin 全量增量Cube的构建 手动触发合并 JDBC 操作 Scala

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 目前已经更新到了&#xff1a; Hadoop&#xff08;已更完&#xff09;HDFS&#xff08;已更完&#xff09;MapReduce&#xff08;已更完&am…...

云手机与传统手机的区别是什么?

随着科技的快速进步&#xff0c;云手机逐渐成为手机市场的热门选择。与传统的智能手机相比&#xff0c;云手机具有许多独特的功能和优势&#xff0c;尤其在多账号管理和高效操作方面备受关注。那么&#xff0c;云手机究竟与普通手机有哪些区别呢&#xff1f; 1. 更灵活的操作与…...

微知-Bluefield DPU命名规则各字段作用?BF2 BF3全系列命名大全

文章目录 背景字段命名C是bmc的意思NOT的N是是否加密S表示不加密但是secureboot enable倒数第四个都是E倒数第五个是速率 V和H是200GM表示E serials&#xff0c;H表示P serials&#xff08;区别参考兄弟篇&#xff1a;[more](https://blog.csdn.net/essencelite/article/detail…...

前端地图开发避坑指南:解决天地图、高德、百度坐标偏移的完整JS方案

前端地图开发避坑指南&#xff1a;解决天地图、高德、百度坐标偏移的完整JS方案 当你在物流轨迹系统中发现GPS设备采集的坐标在高德地图上偏离实际位置500米&#xff0c;或在门店选址工具里百度地图的围栏总是无法匹配真实建筑轮廓时&#xff0c;这背后隐藏着中国地图服务特有…...

如何用FunClip在5分钟内完成AI智能视频剪辑:从零到精通完整指南

如何用FunClip在5分钟内完成AI智能视频剪辑&#xff1a;从零到精通完整指南 【免费下载链接】FunClip Open-source, accurate and easy-to-use video speech recognition & clipping tool, LLM based AI clipping intergrated. 项目地址: https://gitcode.com/GitHub_Tre…...

Linux动态库版本管理:从链接错误到Soname机制详解

1. 从一次“诡异”的链接错误说起那天在服务器上部署一个自己编译的程序&#xff0c;明明libtest.so就躺在当前目录&#xff0c;执行时却弹出了这个让人摸不着头脑的错误&#xff1a;./a.out: error while loading shared libraries: libtest.so.1: cannot open shared object …...

全新UI 阅后即焚V2正式版系统源码_全开源_安全加密传输

概述 在数字化信息交流日益频繁的今天&#xff0c;如何安全、私密地传输敏感数据&#xff08;如商业机密、登录凭证、个人隐私&#xff09;已成为企业和个人用户共同面临的严峻挑战。传统的即时通讯工具往往存在聊天记录留存、云端备份等安全隐患&#xff0c;难以满足“阅后即…...

MindStudio组合技,让Host Bound问题看得见、调得准

背景介绍&#xff1a;Host Bound问题在NPU训练和推理场景中&#xff0c;Host侧&#xff08;CPU&#xff09;的任务下发&#xff08;如算子调度、内存分配&#xff09;与Device侧&#xff08;NPU&#xff09;的任务执行是异步进行的。当Host侧任务下发耗时超过Device侧任务执行耗…...

别再乱改驱动了!手把手教你为RV1126的7寸MIPI屏生成正确的GT911配置文件

RV1126开发实战&#xff1a;GT911触摸屏配置文件的深度解析与精准调试 在嵌入式开发中&#xff0c;触摸屏调试往往是一个令人头疼的问题。特别是当遇到坐标不准、跳点或方向错误时&#xff0c;很多开发者第一反应就是修改驱动代码中的方向参数。然而&#xff0c;这种"头痛…...

创业团队如何借助Taotoken的多模型与透明计费快速验证AI产品原型

&#x1f680; 告别海外账号与网络限制&#xff01;稳定直连全球优质大模型&#xff0c;限时半价接入中。 &#x1f449; 点击领取海量免费额度 创业团队如何借助Taotoken的多模型与透明计费快速验证AI产品原型 对于资源有限的创业团队而言&#xff0c;在产品开发初期快速验证…...

保姆级避坑指南:从模之屋PMX到Unity,搞定Blender导出FBX的纹理丢失问题

保姆级避坑指南&#xff1a;从模之屋PMX到Unity&#xff0c;搞定Blender导出FBX的纹理丢失问题 如果你是一位二次元风格游戏开发者或MMD模型爱好者&#xff0c;那么从模之屋下载PMX模型后&#xff0c;在Blender中处理并导出为FBX格式&#xff0c;最后导入Unity的过程中&#xf…...

深入解析ACP Bridge:构建高效微服务通信与数据同步的协议转换桥梁

1. 项目概述与核心价值最近在折腾一个跨平台数据同步的项目&#xff0c;遇到了一个挺有意思的组件——allvegetable/acp-bridge。乍一看这个名字&#xff0c;可能会有点摸不着头脑&#xff0c;acp是什么&#xff1f;bridge又在这里扮演什么角色&#xff1f;实际上&#xff0c;这…...

无人机巡检避坑指南:用YOLOv5n做罂粟识别,这些光照和遮挡问题怎么解决?

无人机巡检实战&#xff1a;YOLOv5n在复杂环境下的罂粟识别优化策略 清晨的露珠还挂在叶片上&#xff0c;无人机已经盘旋在田野上空。对于从事智能巡检的工程师来说&#xff0c;这样的场景再熟悉不过——但随之而来的挑战也令人头疼&#xff1a;强烈的晨光让部分区域过曝&#…...