UIToast.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { UIViewID } from '@scripts/define/UIDefine';
  2. import { UIView } from '@scripts/framework/ui/UIView';
  3. import { _decorator, Component, find, instantiate, Label, Node, NodePool, tween, Tween, UIOpacity, UITransform, Vec3 } from 'cc';
  4. const { ccclass, property } = _decorator;
  5. @ccclass('UIToast')
  6. export class UIToast extends UIView {
  7. readonly viewId: UIViewID = UIViewID.UIToast;
  8. @property(Node)
  9. toastNode: Node;
  10. private _pool: NodePool;
  11. protected onLoad(): void {
  12. this._pool = new NodePool();
  13. }
  14. show(msg: string) {
  15. const item = this.getToastNode();
  16. item.setMsg(msg, () => { this._pool.put(item.node) });
  17. }
  18. private getToastNode(): ToastCtrl {
  19. let item = this._pool.get();
  20. if (!item) {
  21. item = instantiate(this.toastNode);
  22. }
  23. item.parent = this.node;
  24. item.active = true;
  25. if (!item['_toastCtrl']) {
  26. item['_toastCtrl'] = new ToastCtrl(item);
  27. }
  28. return item['_toastCtrl'];
  29. }
  30. }
  31. class ToastCtrl {
  32. private _lblMsg: Label;
  33. private _lblMsgTrans: UITransform;
  34. private _transform: UITransform;
  35. private _uiOpacity: UIOpacity;
  36. constructor(readonly node: Node) {
  37. this._transform = node.getComponent(UITransform);
  38. this._uiOpacity = node.getComponent(UIOpacity);
  39. const msgNode = find("Label", node);
  40. this._lblMsg = msgNode.getComponent(Label);
  41. this._lblMsgTrans = msgNode.getComponent(UITransform);
  42. }
  43. setMsg(msg: string, onEnd) {
  44. this._lblMsg.string = msg;
  45. const lblWidth = this._lblMsgTrans.width;
  46. this._transform.width = lblWidth + 100;
  47. Tween.stopAllByTarget(this.node);
  48. Tween.stopAllByTarget(this._uiOpacity);
  49. this._uiOpacity.opacity = 0;
  50. this.node.scale = Vec3.ZERO;
  51. this.node.y = 0;
  52. const s1 = tween(this._uiOpacity).to(0.3, { opacity: 255 });
  53. const s2 = tween(this.node).to(0.3, { scale: Vec3.ONE }, { easing: "backOut" });
  54. const e1 = tween(this.node).by(0.5, { y: 100 });
  55. const e2 = tween(this._uiOpacity).delay(0.2).to(0.3, { opacity: 0 });
  56. tween(this.node)
  57. .parallel(s1, s2)
  58. .delay(2)
  59. .parallel(e1, e2)
  60. .call(onEnd)
  61. .start();
  62. }
  63. }