laya list里面物品居中显示
laya list里面里面的物品数量不定, list宽度设置好后, 会从左向右填写, 不会居中对齐.
public list!: Laya.List; alineItems(length:number){ // 根据items数量动态设置list 的位置 // 获取父容器宽度(假设父容器是 this 的宽度) const parentWidth = Laya.stage.width; // 假设每个 item 的宽度是固定的,比如 100(可以根据实际情况调整) const itemWidth = 125; const spacing = 11; // 每个 item 之间的间距 // 计算 list 的总宽度 const totalWidth = length * itemWidth + (length - 1) * spacing; // 计算 list 的 x 坐标,使其居中 const centerX = (parentWidth - totalWidth) / 2; // 修改宽度 this.list.width = totalWidth; // 设置 list 的位置 this.list.pos(centerX, this.list.y); console.log("长度为:" + this.list.array.length + ",总宽度为:" + totalWidth + ",居中位置为:" + centerX); } let arr: any[] = []; let infos = this.additionData; for (let info of infos) { arr.push({ item: PropData.instance.getPropInfoById(info.type).res, num: `x${info.value}` }); } this.list.array = arr; // list设置好了数值, 延迟调用调整位置 this.timer.callLater(this, () => { //调整位置居中 this.alineItems(this.list.array.length); });
注意list的父节点的位置, 这儿list的父节点与stage一样宽, 配置的居中显示.
浙公网安备 33010602011771号