ToastCtrl.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * Toast 控制器
  3. */
  4. cc.Class({
  5. extends: cc.Component,
  6. properties: {
  7. itemPrefab: cc.Prefab,
  8. _holdTime: 2,
  9. _showTime: 0.2,
  10. _hideTime: 0.3,
  11. _totalHeight: 0
  12. },
  13. /**
  14. * 添加一个Toast
  15. *
  16. * @author Pyden
  17. * @date 2019-03-22
  18. * @param {string} msg Toast内容(支持富文本)
  19. * @param {float} holdTime 停留时长(秒)。默认是2秒
  20. */
  21. addToast (msg, holdTime, cb) {
  22. holdTime = holdTime || this._holdTime;
  23. let itemNode = cc.instantiate(this.itemPrefab);
  24. let toastItem = itemNode.getComponent('JMToastItem');
  25. toastItem.msg = msg;
  26. this._showItem(itemNode, holdTime, cb);
  27. },
  28. /**
  29. * 展示一个Toast
  30. *
  31. * @author Pyden
  32. * @date 2019-03-22
  33. * @param {cc.Node} itemNode
  34. * @param {float} holdTime 停留时长(秒)
  35. */
  36. _showItem (itemNode, holdTime, cb) {
  37. // toastRoot向上移动
  38. let itemHeight = itemNode.height;
  39. // 总高度
  40. this._totalHeight = this._totalHeight + itemHeight;
  41. this.node.stopAllActions();
  42. cc.tween(this.node)
  43. .to(this._showTime, {position: cc.v2(0, this._totalHeight - itemHeight / 2)})
  44. .start();
  45. // 节点一直往下排列
  46. itemNode.y = -this._totalHeight + itemHeight / 2;
  47. this.node.addChild(itemNode);
  48. itemNode.opacity = 0;
  49. cc.tween(itemNode)
  50. .to(this._showTime, {opacity: 255}) // 淡出
  51. .delay(holdTime) // 停留
  52. .to(this._hideTime, {opacity: 0}) // 淡出
  53. .call(() => {
  54. itemNode.destroy(); // 销毁
  55. if (cb) {
  56. cb();
  57. }
  58. }).start();
  59. }
  60. });