NativeScript Dialogs 模块完全指南:alert、confirm、prompt、login、action 与自定义对话框

发布时间:2026/10/1 1:55:10
NativeScript Dialogs 模块完全指南:alert、confirm、prompt、login、action 与自定义对话框
【免费下载链接】NativeScript⚡ Write Native with TypeScript ✨ Best of all worlds (TypeScript, Swift, Objective C, Kotlin, Java, Dart). Use what you love ❤️ Angular, React, Solid, Svelte, Vue with: iOS (UIKit, SwiftUI), Android (View, Jetpack Compose), Flutter and you name it compatible.项目地址https://gitcode.com/gh_mirrors/na/NativeScript点击查看免费下载本文以 NativeScript 核心包中的 dialogs 模块packages/core/ui/dialogs/Readme.md为骨架系统讲解alert、confirm、prompt、login、action五大内置对话框 API 以及自定义 Dialog 的用法。读者将掌握每个 API 的函数签名、可选参数、Promise 返回值语义以及这些 API 在 AndroidAlertDialog.Builder与 iOSUIAlertController底层的实现差异可直接在真实项目中落地使用。模块引入与使用前提所有对话框 API 都位于ui/dialogs模块中。在 NativeScript 应用中需要先引入全局 polyfill 与对话框模块require(globals); var dialogs require(ui/dialogs);在 TypeScript 项目中则直接使用 ES 模块导入import { alert, confirm, prompt, login, action } from nativescript/core/ui/dialogs;模块同时导出一个聚合对象Dialogs{ alert, confirm, prompt, login, action }方便一次性引入全部方法定义于 index.android.ts 与 index.ios.ts。apps/automated/src/ui/dialogs/dialogs.md中同样确认显示对话框必须先引入ui/dialogs模块并依次演示了 Action、Confirm、Alert、Login、Prompt 五个场景。API 总览五大方法签名完整的方法签名定义在 packages/core/ui/dialogs/index.d.ts 中方法返回 Promise说明alert(message)/alert(options)Promisevoid显示只有 OK 按钮的提示框confirm(message)/confirm(options)Promiseboolean显示确认框返回用户选择prompt(message, defaultText?)/prompt(options)PromisePromptResult带文本输入框的对话框login(message, userNameHint?, passwordHint?, userName?, password?)/login(options)PromiseLoginResult带用户名/密码两个输入框的登录框action(message, cancelButtonText, actions)/action(options)Promisestring列出多个操作项供用户选择每个方法都提供了两种调用形态传入字符串消息或传入完整的 Options 对象。所有方法均返回 Promise因此既可以用.then()链式调用也可以配合async/await使用。Alert最简单的提示框alert用于显示一条消息和 OK 按钮是最常用的反馈手段dialogs.alert(Some message) .then(function () { dialogs.alert(Alert closed!); });带自定义标题与按钮文案dialogs.alert(Some message, { title: My custom title, okButtonText: Close }) .then(function () { dialogs.alert(Alert closed!); });alert的第二个参数实际是AlertOptions对象支持的字段包括title、message、okButtonText继承自DialogOptions的title/message以及CancelableOptions的cancelable/theme见 dialogs-common.ts。alert在用户点击 OK 或关闭对话框后 resolve不返回业务数据。从 Android 实现看index.android.tsalert使用android.app.AlertDialog.Builder创建对话框并设置 PositiveButtoniOS 端index.ios.ts则基于UIAlertControllerUIAlertControllerStyle.Alert实现。Confirm二态/三态确认confirm返回Promiseboolean用户点击 OK 得到true点击 Cancel 得到falsedialogs.confirm(Some question?).then(function (r) { dialogs.alert(Result: r); }); dialogs.confirm(Some question?, { title: My custom title, okButtonText: Yes, cancelButtonText: No }) .then(function (r) { dialogs.alert(Result: r); }); dialogs.confirm(Some question?, { title: My custom title, okButtonText: Yes, cancelButtonText: No, neutralButtonText: Not sure }) .then(function (r) { dialogs.alert(Result: r); });ConfirmOptions在AlertOptions基础上增加了cancelButtonText与neutralButtonTextdialogs-common.ts。当提供neutralButtonText时出现第三个中立按钮其回调结果为undefined——这正是r取值需要区分true、false、undefined三种情况的原因。底层行为有明确的平台差异值得开发者注意Androidindex.android.tsPositive 按钮回调true、Negative 按钮回调false、Neutral 按钮回调undefined同时注册了OnDismissListener对话框被取消点击外部区域、按返回键时回调false。iOSindex.ios.tsCancel 按钮回调false、Neutral 回调undefined、OK 回调true且 OK 按钮被设为preferredAction支持用键盘回车键确认对话框。Prompt带输入框的对话框prompt返回PromisePromptResult其中result为布尔结果text为用户输入的文字dialogs.prompt(Some message) .then(function (r) { dialogs.alert(Boolean result: r.result , entered text: r.text); }) .fail(function (e) { console.log(e) });第二个参数可作为输入框的默认文本第三个参数传入PromptOptionsdialogs.prompt(Some message, Default text for the input, { title: My custom title, okButtonText: Yes, cancelButtonText: No, neutralButtonText: Not sure, inputType: dialogs.InputType.Password }).then(function (r) { dialogs.alert(Boolean result: r.result , entered text: r.text); });PromptOptions在ConfirmOptions基础上新增三个字段dialogs-common.ts字段类型说明defaultTextstring输入框的默认/预填文本inputTypestring输入类型见下方枚举capitalizationTypestring自动大写策略见下方枚举inputType与capitalizationType的取值分别由dialogs.InputType和dialogs.CapitalizationType枚举定义源码位于 dialogs-common.tsInputTypetext纯文本、password密码、email、number、decimal、phoneCapitalizationTypenone不自动大写、all每个字符都大写、sentences句首大写、words每个单词首字母大写注意prompt未指定inputType时默认使用inputType.textAndroid 与 iOS 两端的默认选项都包含这一设置index.android.ts、index.ios.ts。输入类型的平台映射也值得了解Android 端通过EditText.setInputType()设置如password→TYPE_TEXT_VARIATION_PASSWORDemail→TYPE_TEXT_VARIATION_EMAIL_ADDRESSnumber→TYPE_CLASS_NUMBERdecimal→TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMALphone→TYPE_CLASS_PHONE见 index.android.tsiOS 端通过UITextField的secureTextEntry密码与keyboardType邮箱、数字、小数、电话键盘实现index.ios.ts。Login用户名与密码输入login返回PromiseLoginResult其结构为{ result: boolean, userName: string, password: string }dialogs-common.tsdialogs.login(Enter your user name and password:).then(function(r) { dialogs.alert(Result: r.result User name: r.userName Password: r.password); });带完整的自定义选项dialogs.login(Enter your user name and password:, , , { title: Login, okButtonText: Sign In, cancelButtonText: Cancel, neutralButtonText:Sign Up }) .then(function(r) { dialogs.alert(Result: r.result User name: r.userName Password: r.password); if(r.result) { // login here } else if(r.result false) { // perform something on cancel if you want } else if(r.result undefined) { // you can create new user credentials here for example } }).fail(function(e){ console.log(e)});LoginOptions在ConfirmOptions基础上提供userNameHint、passwordHint输入框占位提示、userName、password预填值四个字段dialogs-common.ts。关于r.result三态判断需要强调示例代码中的r.result undefined是原文档的写法实际运行时中性按钮回调的值为undefined布尔/未定义值更稳妥的判断方式是r.result undefined。在 Android 与 iOS 实现中中性按钮neutralButtonText的回调结果均为undefined与 confirm 的行为保持一致。位置参数与 Options 对象的解析由parseLoginOptions完成dialogs-common.ts当只传入一个对象参数时直接作为LoginOptions使用否则依次将五个位置参数映射为message、userNameHint、passwordHint、userName、password标题默认Login、OK 默认OK、Cancel 默认Cancel。平台实现要点Android 端创建两个EditText密码框设置TYPE_TEXT_VARIATION_PASSWORD并放入垂直LinearLayout见 index.android.tsiOS 端通过addTextFieldWithConfigurationHandler添加两个文本框第二个文本框设置secureTextEntry trueindex.ios.ts。Action多选项列表action用于弹出操作列表返回用户所选字符串Promisestringdialogs.action(Some message, Cancel, [Option 1, Option 2]) .then(function (r) { dialogs.alert(Result: r); });ActionOptions支持title、message、cancelButtonText、actions字符串数组以及 iOS 专用的destructiveActionsIndexes标记哪些索引的操作项为破坏性样式见 dialogs-common.ts。平台差异显著Androidindex.android.ts使用AlertDialog.Builder的setItems()展示操作列表点击某项即 resolve 该项文本点击取消按钮或 dismiss 时 resolve 取消按钮文本。iOSindex.ios.ts使用UIAlertControllerStyle.ActionSheet弹出底部操作表被destructiveActionsIndexes标记的操作项使用UIAlertActionStyle.Destructive样式红色取消项使用UIAlertActionStyle.Cancel。对话框的样式与主题控制所有对话框 Options 均继承自CancelableOptionsdialogs-common.ts提供两个平台相关字段cancelable?: booleanAndroid only是否允许点击对话框外部区域关闭对话框为false时禁用。Android 实现中通过alert.setCancelable(false)生效index.android.ts。theme?: numberAndroid only指定android.app.AlertDialog.Builder的主题资源 IDindex.android.ts可参考 Android 的android.R.style主题常量。此外对话框会继承当前页面的 CSS 样式作用域dialogs-common.ts中的applySelectors会让按钮、标签、文本框继承当前页面_styleScope的样式dialogs-common.ts并通过getButtonColors、getLabelColor、getTextFieldColor将计算后的颜色应用到原生对话框控件上。Android 端在showDialog中为标题、消息、按钮设置文字颜色与背景色index.android.tsiOS 端则通过view.tintColor与NSAttributedString应用按钮与标题颜色index.ios.ts。这意味着你可以在页面 CSS 中统一控制对话框的文字与按钮配色。自定义对话框Dialog 类除了内置的五种对话框文档还演示了通过dialogs.Dialog类创建自定义对话框如启动屏Loading...提示require(globals); var dialogs require(ui/dialogs); /// Splash var d new dialogs.Dialog(Loading...); d.show(); setTimeout(function(){ d.hide(); }, 2000); //or cancelable loading dialog var d new dialogs.Dialog(Loading..., function(r){ dialogs.alert(You just canceled loading!); }, { cancelButtonText: Cancel }); d.show(); setTimeout(function(){ d.hide(); }, 10000);Dialog构造函数的三个参数分别为显示的消息文本、取消时的回调函数、以及可选的取消按钮配置cancelButtonText。show()展示对话框hide()关闭它。由于对话框 API 均返回 Promise 且Dialog类的可用性以当前使用版本为准原文档保留了该示例在需要复杂自定义 UI 时也可以考虑使用nativescript/core的modal或showModal机制承载自定义页面以获得完整的布局与交互自由度。常见问题与使用建议确认/登录结果的undefined判断确认框与登录框在用户点击中性按钮neutralButtonText时结果为undefined与false取消语义不同业务代码应区分处理。fail回调示例中.fail(function (e) { console.log(e) })用于捕获对话框创建失败等异常在 Promise 规范下同样可以使用.catch()。在页面加载前调用对话框依赖当前页面Android 需要getCurrentActivity()iOS 需要 rootViewController若在应用启动早期、页面尚未就绪时调用可能找不到承载控制器建议在页面事件回调中触发可参考 dialogs-common.ts 的getCurrentPage与 iOS 端对 rootViewController 的查找逻辑 index.ios.ts。对话框与页面样式联动利用页面 CSS 与applySelectors机制可让对话框按钮、文字颜色与 App 主题保持一致。参考资源模块文档packages/core/ui/dialogs/Readme.md自动化测试参考apps/automated/src/ui/dialogs/dialogs.md类型声明与 Options 接口packages/core/ui/dialogs/index.d.ts平台无关实现与参数解析packages/core/ui/dialogs/dialogs-common.tsAndroid 实现packages/core/ui/dialogs/index.android.tsiOS 实现packages/core/ui/dialogs/index.ios.ts赞分享【免费下载链接】NativeScript⚡ Write Native with TypeScript ✨ Best of all worlds (TypeScript, Swift, Objective C, Kotlin, Java, Dart). Use what you love ❤️ Angular, React, Solid, Svelte, Vue with: iOS (UIKit, SwiftUI), Android (View, Jetpack Compose), Flutter and you name it compatible.项目地址https://gitcode.com/gh_mirrors/na/NativeScript点击查看免费下载相关推荐Svelte Native 对话框使用指南Action、Alert、Confirm、Login 和 Prompt 详解Svelte Native 对话框使用指南Action、Alert、Confirm、Login 和 Prompt 详解 前言 在移动应用开发中对话框是与用户aiohttp 3.0 新特性深度解析async/await 全面化、应用运行器与客户端请求追踪aiohttp 3.0 新特性深度解析async/await 全面化、应用运行器与客户端请求追踪 导读 本文基于仓库中的官方发布说明 docs/whats_n后端Web框架WebSocketMaterial Design Lite模态对话框Alert、Confirm、Prompt实现终极指南Material Design Lite模态对话框Alert、Confirm、Prompt实现终极指南 Material Design LiteMDL的前端UI组件上一篇为你的Unity项目增添科技色彩Wireframe Shader 2021.3.unitypackage下一篇Qwen2-0.5B-ITA-Instruct应用场景10个实用的意大利语AI任务创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考