【免费下载链接】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.
本文以 NativeScript 核心包中的 dialogs 模块(packages/core/ui/dialogs/Readme.md)为骨架,系统讲解alert、confirm、prompt、login、action五大内置对话框 API 以及自定义 Dialog 的用法。读者将掌握每个 API 的函数签名、可选参数、Promise 返回值语义,以及这些 API 在 Android(AlertDialog.Builder)与 iOS(UIAlertController)底层的实现差异,可直接在真实项目中落地使用。
模块引入与使用前提
所有对话框 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) | Promise<void> | 显示只有 OK 按钮的提示框 |
confirm(message)/confirm(options) | Promise<boolean> | 显示确认框,返回用户选择 |
prompt(message, defaultText?)/prompt(options) | Promise<PromptResult> | 带文本输入框的对话框 |
login(message, userNameHint?, passwordHint?, userName?, password?)/login(options) | Promise<LoginResult> | 带用户名/密码两个输入框的登录框 |
action(message, cancelButtonText, actions)/action(options) | Promise<string> | 列出多个操作项供用户选择 |
每个方法都提供了两种调用形态:传入字符串消息,或传入完整的 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.ts),alert使用android.app.AlertDialog.Builder创建对话框并设置 PositiveButton;iOS 端(index.ios.ts)则基于UIAlertController(UIAlertControllerStyle.Alert)实现。
Confirm:二态/三态确认
confirm返回Promise<boolean>,用户点击 OK 得到true,点击 Cancel 得到false:
dialogs.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与neutralButtonText(dialogs-common.ts)。当提供neutralButtonText时出现第三个"中立"按钮,其回调结果为undefined——这正是r取值需要区分true、false、undefined三种情况的原因。
底层行为有明确的平台差异,值得开发者注意:
- Android(index.android.ts):Positive 按钮回调
true、Negative 按钮回调false、Neutral 按钮回调undefined;同时注册了OnDismissListener,对话框被取消(点击外部区域、按返回键)时回调false。 - iOS(index.ios.ts):Cancel 按钮回调
false、Neutral 回调undefined、OK 回调true;且 OK 按钮被设为preferredAction,支持用键盘回车键确认对话框。
Prompt:带输入框的对话框
prompt返回Promise<PromptResult>,其中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) });第二个参数可作为输入框的默认文本,第三个参数传入PromptOptions:
dialogs.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):
| 字段 | 类型 | 说明 |
|---|---|---|
defaultText | string | 输入框的默认/预填文本 |
inputType | string | 输入类型,见下方枚举 |
capitalizationType | string | 自动大写策略,见下方枚举 |
inputType与capitalizationType的取值分别由dialogs.InputType和dialogs.CapitalizationType枚举定义(源码位于 dialogs-common.ts):
- InputType:
text(纯文本)、password(密码)、email、number、decimal、phone - CapitalizationType:
none(不自动大写)、all(每个字符都大写)、sentences(句首大写)、words(每个单词首字母大写)
注意:prompt未指定inputType时默认使用inputType.text,Android 与 iOS 两端的默认选项都包含这一设置(index.android.ts、index.ios.ts)。
输入类型的平台映射也值得了解:Android 端通过EditText.setInputType()设置(如password→TYPE_TEXT_VARIATION_PASSWORD,email→TYPE_TEXT_VARIATION_EMAIL_ADDRESS,number→TYPE_CLASS_NUMBER,decimal→TYPE_CLASS_NUMBER | TYPE_NUMBER_FLAG_DECIMAL,phone→TYPE_CLASS_PHONE,见 index.android.ts);iOS 端通过UITextField的secureTextEntry(密码)与keyboardType(邮箱、数字、小数、电话键盘)实现(index.ios.ts)。
Login:用户名与密码输入
login返回Promise<LoginResult>,其结构为{ result: boolean, userName: string, password: string }(dialogs-common.ts):
dialogs.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.ts);iOS 端通过addTextFieldWithConfigurationHandler添加两个文本框,第二个文本框设置secureTextEntry = true(index.ios.ts)。
Action:多选项列表
action用于弹出操作列表,返回用户所选字符串Promise<string>:
dialogs.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)。
平台差异显著:
- Android(index.android.ts):使用
AlertDialog.Builder的setItems()展示操作列表,点击某项即 resolve 该项文本;点击取消按钮或 dismiss 时 resolve 取消按钮文本。 - iOS(index.ios.ts):使用
UIAlertControllerStyle.ActionSheet弹出底部操作表,被destructiveActionsIndexes标记的操作项使用UIAlertActionStyle.Destructive样式(红色),取消项使用UIAlertActionStyle.Cancel。
对话框的样式与主题控制
所有对话框 Options 均继承自CancelableOptions(dialogs-common.ts),提供两个平台相关字段:
cancelable?: boolean:Android only,是否允许点击对话框外部区域关闭对话框;为false时禁用。Android 实现中通过alert.setCancelable(false)生效(index.android.ts)。theme?: number:Android only,指定android.app.AlertDialog.Builder的主题资源 ID(index.android.ts),可参考 Android 的android.R.style主题常量。
此外,对话框会继承当前页面的 CSS 样式作用域:dialogs-common.ts中的applySelectors会让按钮、标签、文本框继承当前页面_styleScope的样式(dialogs-common.ts),并通过getButtonColors、getLabelColor、getTextFieldColor将计算后的颜色应用到原生对话框控件上。Android 端在showDialog中为标题、消息、按钮设置文字颜色与背景色(index.android.ts);iOS 端则通过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.ts
- Android 实现:packages/core/ui/dialogs/index.android.ts
- iOS 实现: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.
相关推荐
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 Lite(MDL)的
前端UI组件
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考