优化Framework.UI新增便捷接口

This commit is contained in:
janing
2025-12-14 23:35:54 +08:00
parent d530b48e34
commit 1d91daa726
5 changed files with 285 additions and 1742 deletions

View File

@@ -1,4 +1,4 @@
import { Node } from 'cc';
import { Node, Component, Button } from 'cc';
/**
* UI基类
@@ -121,4 +121,67 @@ export abstract class UIBase {
isLoaded(): boolean {
return this._isLoaded;
}
/**
* 查找子节点并获取组件
* @param path 节点路径,支持多层级查找(如: 'mid/input_account')
* @param componentType 组件类型
* @returns 组件实例,未找到则返回null
* @example
* const editBox = this.GetChild('mid/input_account', EditBox);
* const button = this.GetChild('btn_login', Button);
*/
protected GetChild<T extends Component>(path: string, componentType: { new(): T }): T | null {
if (!this._node) {
console.error('[UIBase] GetChild失败: UI根节点不存在');
return null;
}
const childNode = this._node.getChildByPath(path);
if (!childNode) {
console.error(`[UIBase] GetChild失败: 未找到节点 ${path}`);
return null;
}
const component = childNode.getComponent(componentType);
if (!component) {
console.error(`[UIBase] GetChild失败: 节点 ${path} 未挂载 ${componentType.name} 组件`);
return null;
}
return component;
}
/**
* 设置按钮点击事件
* @param button Button组件或包含Button组件的Node
* @param callback 点击回调函数
* @param target 回调函数的this指向
* @example
* const btn = this.GetChild('btn_login', Button);
* this.SetClick(btn, this.onLoginClick, this);
*/
protected SetClick(button: Button | Node | null, callback: () => void, target?: any): void {
if (!button) {
console.error('[UIBase] SetClick失败: button为null');
return;
}
let targetNode: Node | null = null;
// 判断是Button组件还是Node
if (button instanceof Button) {
targetNode = button.node;
} else if (button instanceof Node) {
targetNode = button;
}
if (!targetNode) {
console.error('[UIBase] SetClick失败: 无法获取目标节点');
return;
}
// 绑定点击事件
targetNode.on(Node.EventType.TOUCH_END, callback, target);
}
}