72 lines
1.6 KiB
TypeScript
72 lines
1.6 KiB
TypeScript
import { _decorator, Component, Label } from 'cc';
|
|
import { I18nManager } from '../manager/I18nManager';
|
|
|
|
const { ccclass, property, executeInEditMode } = _decorator;
|
|
|
|
@ccclass('LocalizedLabel')
|
|
@executeInEditMode
|
|
export class LocalizedLabel extends Component {
|
|
private label: Label | null = null;
|
|
|
|
@property({ visible: false })
|
|
private _key: string = '';
|
|
|
|
@property({
|
|
displayName: 'Key',
|
|
tooltip: '多语言翻译键值'
|
|
})
|
|
get key() {
|
|
return this._key;
|
|
}
|
|
|
|
set key(value: string) {
|
|
this._key = value;
|
|
this.updateLabel();
|
|
}
|
|
|
|
onLoad() {
|
|
// 确保 I18nManager 已初始化
|
|
if (I18nManager.instance.ready) {
|
|
this.fetchRender();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取Label组件并更新文本
|
|
*/
|
|
fetchRender() {
|
|
if (!this.label) {
|
|
this.label = this.getComponent(Label);
|
|
}
|
|
|
|
if (this.label) {
|
|
this.updateLabel();
|
|
} else {
|
|
console.warn(`LocalizedLabel: No Label component found on node ${this.node.name}`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 更新标签文本
|
|
*/
|
|
public updateLabel() {
|
|
if (!this.label || !this._key) return;
|
|
|
|
const i18nManager = I18nManager.instance;
|
|
const translatedText = i18nManager.t(this._key);
|
|
|
|
if (this.label.string !== translatedText) {
|
|
this.label.string = translatedText;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 手动设置翻译键值并更新文本
|
|
*/
|
|
public setKey(key: string) {
|
|
if (this._key !== key) {
|
|
this._key = key;
|
|
this.updateLabel();
|
|
}
|
|
}
|
|
} |