Nanfeng

Notes on software development, code, and curious ideas

Cocos Creator Dynamic PageView: addPage, removePage and Change Events

This example demonstrates runtime page creation, page removal, and PageView change events.

Dynamic PageView Logic

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
import { _decorator, Node, UITransform, size } from 'cc';
import { UIPnlMultiTableView } from './UIPnlMultiTableView';
import { UIBaseLogic } from '../../UIBaseLogic';

export class UIPnlMultiTableLogic extends UIBaseLogic {
public static prefabPath = '/prefab/ui/multiTable/PnlMultiTable';
public _view: UIPnlMultiTableView;

public Init(id: string, go: Node) {
this._view = new UIPnlMultiTableView(go);
super.Init(id, go);
}

public BindUIEvent() {
this.BindUIEventClick(this._view._Btn_add.node, this.HandlerBtn_add);
this.BindUIEventClick(this._view._Btn_del.node, this.HandlerBtn_del);
this._view._PageC_table.node.on(
'page-turning',
this.printCurrentPageIndex,
this
);
}

private HandlerBtn_add() {
const newPageNode = new Node('NewPageNode');
const transform = newPageNode.addComponent(UITransform);
transform.setContentSize(size(1624, 750));
this._view._PageC_table.addPage(newPageNode);
newPageNode.parent = this._view._PageC_table.node
.getChildByName('view')
.getChildByName('content');
}

private HandlerBtn_del() {
const index = this._view._PageC_table.getCurrentPageIndex();
const page = this._view._PageC_table.getPages()[index];
if (page) this._view._PageC_table.removePage(page);
}

private printCurrentPageIndex() {
const index = this._view._PageC_table.getCurrentPageIndex();
console.log('Current Page Index:', index);
}
}

PageView Component References

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Node, Button, PageView } from 'cc';

export class UIPnlMultiTableView {
public _root: Node;
public _Nego_Root: Node;
public _PageC_table: PageView;
public _Btn_add: Button;
public _Btn_del: Button;

constructor(go: Node) {
this._root = go;
this._Nego_Root = go.getChildByPath('Nego_Root');
this._PageC_table = go
.getChildByPath('Nego_Root/PageC_table')
.getComponent(PageView);
this._Btn_add = go
.getChildByPath('Nego_Root/Btn_add')
.getComponent(Button);
this._Btn_del = go
.getChildByPath('Nego_Root/Btn_del')
.getComponent(Button);
}
}

Remember to unregister page-turning when the owning component or view is destroyed.

+