Nanfeng

Notes on software development, code, and curious ideas

Getting an Updated Label Size in Cocos Creator 3.7.2

To obtain a label’s updated dimensions after changing its text, wait until the label has processed or rendered the new content before reading its UITransform.

Change the label text

1
2
3
const labelNode = this.node.getChildByName("LabelNode");
const labelComponent = labelNode.getComponent(cc.Label);
labelComponent.string = "New label content";

Replace LabelNode with the actual node name used by your scene.

Wait for the update

Scheduling the size read allows the label layout to refresh first:

1
2
3
4
5
6
7
8
director.getScheduler().schedule(() => {
director.getScheduler().unscheduleAllForTarget(labelComponent);

const transform = labelComponent.node.getComponent(UITransform);
const width = transform.width;
const height = transform.height;
transform.setContentSize(width, height);
}, labelComponent, 0, 0);

For modern Cocos Creator code, also consider scheduleOnce or waiting until the next frame, depending on when your surrounding layout updates.

+