如何在Cocos Creator中实现PageView的动态添加、删除和事件处理 | 南锋

南锋

南奔万里空,脱死锋镝余

如何在Cocos Creator中实现PageView的动态添加、删除和事件处理

代码主要介绍了PageView在使用时动态创建、删除page页以及PageView的监听事件

逻辑代码

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

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)
// --------- your code
}

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() { // 添加page页
const newPageNode = new Node("NewPageNode");
const ui = newPageNode.addComponent(UITransform);
ui.setContentSize(size(1624 ,750));
this._view._PageC_table.addPage(newPageNode);
newPageNode.parent = this._view._PageC_table.node.getChildByName("view").getChildByName("content");
}

private HandlerBtn_del() { // 删除page页
const currentPageIndex = this._view._PageC_table.getCurrentPageIndex();
const pageNode = this._view._PageC_table.getPages()[currentPageIndex];
this._view._PageC_table.removePage(pageNode);
}

private printCurrentPageIndex(){ // 添加事件监听,以在页面切换时打印当前页面索引
const currentPageIndex = this._view._PageC_table.getCurrentPageIndex();
console.log("Current Page Index:", currentPageIndex);
}
}

ui部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { _decorator, 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)
}
}
+