PageView.ts 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const { ccclass, property } = cc._decorator;
  2. /**
  3. * 翻页组件类
  4. * - 简单版 无动态加载功能
  5. * - 已知bug,请注意规避:开启回弹后,首尾界面回弹没有考虑 setCurrentPageIndex 导致在setCurrentPageIndex设置之后的位置开始回弹。解决方法:关闭回弹
  6. * @author 薛鸿潇
  7. */
  8. @ccclass
  9. export default class PageView extends cc.Component {
  10. /** 翻页组件 */
  11. private comp_page_view: cc.PageView = null;
  12. /** item 容器 */
  13. private arr_node_item: Array<cc.Node> = [];
  14. onLoad() {
  15. this.comp_page_view = this.node.getComponent(cc.PageView);
  16. this.node.on('ui-init', this.init, this);// 初始化列表
  17. this.node.on('ui-clearItem', this.clearItem, this);// 清除页面
  18. this.node.on('ui-backCurPage', this.backCurPage, this);// 返回到当前Index对应的界面【滑动后禁用滑动功能,再打开滑动功能,翻页组件不会自动返回,调用此接口】
  19. }
  20. start() {
  21. }
  22. /**
  23. * 初始化列表
  24. * @param list_data 数据列表
  25. * @param page_item item预制体
  26. */
  27. private init(list_data: Array<any>, page_item: cc.Prefab, init_index: number = 0) {
  28. const data_count = list_data.length;
  29. if (!data_count) {
  30. // 刷新时,数据列表是空的
  31. const node_count = this.arr_node_item.length;
  32. for (let i = 0; i < node_count; i++) {
  33. this.comp_page_view.removePageAtIndex(i);
  34. this.arr_node_item.splice(i, 1);
  35. }
  36. return;
  37. }
  38. for (let i = 0; i < data_count; i++) {
  39. let node_item = this.arr_node_item[i];
  40. if (!node_item) {
  41. node_item = cc.instantiate(page_item);
  42. this.arr_node_item.push(node_item);
  43. }
  44. // node_item.parent = this.content;
  45. this.comp_page_view.addPage(node_item);
  46. node_item.getComponent(node_item.name).setItemData(list_data[i]);
  47. }
  48. this.comp_page_view.setCurrentPageIndex(init_index);
  49. // 清理多出来的item
  50. const node_count = this.arr_node_item.length;
  51. if (data_count > node_count) {
  52. for (let i = data_count; i < node_count; i++) {
  53. this.comp_page_view.removePageAtIndex(i);
  54. this.arr_node_item.splice(i, 1);
  55. }
  56. }
  57. }
  58. /**
  59. * 返回当前页
  60. */
  61. private backCurPage() {
  62. let index = this.comp_page_view.getCurrentPageIndex();
  63. this.comp_page_view.setCurrentPageIndex(index);
  64. }
  65. /** 清理子节点
  66. * - need_destroy 销毁
  67. */
  68. private clearItem(need_destroy: boolean = false) {
  69. // this.comp_page_view.removeAllPages();
  70. // const n_count = this.arr_node_item.length;
  71. // for (let i = 0; i < n_count; i++) {
  72. // if (need_destroy) {
  73. // let node_end = this.arr_node_item.pop();
  74. // node_end.destroy();
  75. // } else {
  76. // this.arr_node_item[i].removeFromParent();
  77. // }
  78. // }
  79. }
  80. // update (dt) {}
  81. }