showModal.uts 2.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
import { UTSiOS } from "DCloudUTSFoundation"
import { DispatchQueue } from 'Dispatch';
import { DCAlertAction, DCAlertActionStyle, DCAlertView, DCAlertViewControllerStyle } from "DCloudAlertController"  assert { type: "implementationOnly" };
import { ShowModalOptions, ShowModalSuccess, ShowModalFail } from '../interface.uts'

export function toShowModal(options: ShowModalOptions) {
	// 参数解析
	const title = options.title == null ? "" : options.title!
	const message = options.content == null ? "" : options.content!
	const showCancel = options.showCancel == null ? true : (options.showCancel != false)
	const cancelText = options.cancelText == null ? "取消" : options.cancelText!
	const confirmText = options.confirmText == null ? "确定" : options.confirmText!
	const canEidt = options.editable == null ? false : (options.editable != false)
	const placeholderText = options.placeholderText == null ? "" : options.placeholderText!

	// uts方法默认会在子线程中执行,涉及 UI 操作必须在主线程中运行,通过 DispatchQueue.main.async 方法可将代码在主线程中运行
	DispatchQueue.main.async(execute = (): void => {

		// 初始化 DCAlertView 实例对象 alert
		const style: DCAlertViewControllerStyle = canEidt ? DCAlertViewControllerStyle.textViewAlert : DCAlertViewControllerStyle.alert
		const alert = DCAlertView.init(title, message, style, placeholderText)
		
		// 取消按钮及其回调
		if (showCancel) {
			const cancelAction = DCAlertAction.init(title = cancelText, style = DCAlertActionStyle.cancelStyle, handler = (action: DCAlertAction): void => {
				// 获取输入框中的内容
				let inputText = ""
				if (canEidt == true) {
					inputText = alert.textView?.text ?? ""
				}
				// 点击按钮的回调方法
				const res: ShowModalSuccess = {
					confirm: true,
					cancel: false,
					content: inputText
				}
				options.success?.(res)
				options.complete?.(res)
			})
			// 自定义取消按钮颜色
			if (options.cancelColor != null) {
				const color = UTSiOS.colorWithString(options.cancelColor!)
				cancelAction.titleColor = color
			}
			// 添加action
			alert.addAction(cancelAction)
		}
		
		// 确定按钮及其回调
		const okAction = DCAlertAction.init(title = confirmText, style = DCAlertActionStyle.preferredStyle, handler = (action: DCAlertAction): void => {
			// 获取输入框中的内容
			let inputText = ""
			if (canEidt == true) {
				inputText = alert.textView?.text ?? ""
			}
			
			// 点击按钮的回调方法
			const res: ShowModalSuccess = {
				confirm: true,
				cancel: false,
				content: inputText
			}
			options.success?.(res)
			options.complete?.(res)
		})
		// 自定义确定按钮颜色
		if (options.confirmColor != null) {
			const color = UTSiOS.colorWithString(options.confirmColor!)
			okAction.titleColor = color
		}
		// 添加action
		alert.addAction(okAction)
		
		// 弹出alert
		alert.show()
	})
}