import { UIViewID } from '@scripts/define/UIDefine'; import { UIView } from '@scripts/framework/ui/UIView'; import { _decorator, Component, find, instantiate, Label, Node, NodePool, tween, Tween, UIOpacity, UITransform, Vec3 } from 'cc'; const { ccclass, property } = _decorator; @ccclass('UIToast') export class UIToast extends UIView { readonly viewId: UIViewID = UIViewID.UIToast; @property(Node) toastNode: Node; private _pool: NodePool; protected onLoad(): void { this._pool = new NodePool(); } show(msg: string) { const item = this.getToastNode(); item.setMsg(msg, () => { this._pool.put(item.node) }); } private getToastNode(): ToastCtrl { let item = this._pool.get(); if (!item) { item = instantiate(this.toastNode); } item.parent = this.node; item.active = true; if (!item['_toastCtrl']) { item['_toastCtrl'] = new ToastCtrl(item); } return item['_toastCtrl']; } } class ToastCtrl { private _lblMsg: Label; private _lblMsgTrans: UITransform; private _transform: UITransform; private _uiOpacity: UIOpacity; constructor(readonly node: Node) { this._transform = node.getComponent(UITransform); this._uiOpacity = node.getComponent(UIOpacity); const msgNode = find("Label", node); this._lblMsg = msgNode.getComponent(Label); this._lblMsgTrans = msgNode.getComponent(UITransform); } setMsg(msg: string, onEnd) { this._lblMsg.string = msg; const lblWidth = this._lblMsgTrans.width; this._transform.width = lblWidth + 100; Tween.stopAllByTarget(this.node); Tween.stopAllByTarget(this._uiOpacity); this._uiOpacity.opacity = 0; this.node.scale = Vec3.ZERO; this.node.y = 0; const s1 = tween(this._uiOpacity).to(0.3, { opacity: 255 }); const s2 = tween(this.node).to(0.3, { scale: Vec3.ONE }, { easing: "backOut" }); const e1 = tween(this.node).by(0.5, { y: 100 }); const e2 = tween(this._uiOpacity).delay(0.2).to(0.3, { opacity: 0 }); tween(this.node) .parallel(s1, s2) .delay(2) .parallel(e1, e2) .call(onEnd) .start(); } }