import SScript from "./SScript"; import Sprite = Laya.Sprite; import Node = Laya.Node; import UIComponent = Laya.UIComponent; export default class SContainer extends SScript{ private _backgroundImg: UIComponent; private _paddingBottom: number = 0; private _paddingRight: number = 0; onAwake(){ let o:UIComponent = this.owner as UIComponent; this._backgroundImg = o.getChildByName('bg') as UIComponent; if(this._backgroundImg)this._backgroundImg.left = this._backgroundImg.right = this._backgroundImg.top = this._backgroundImg.bottom = 0; let origiAddChild:Function = o.addChild; let addResizeListener = (child:Node)=>{ child.on(Laya.Event.RESIZE, this, this._prepareToRefresh); }; let removeResizeListener = (child:Node)=>{ child.off(Laya.Event.RESIZE, this, this._prepareToRefresh); }; o.addChild = function(child:Node):Node{ if (!child || this.destroyed || child===this)return child; addResizeListener(child); return origiAddChild.call(this, child); }; let origiAddChildAt = o.addChildAt; o.addChildAt = function(child:Node, index:number):Node{ if (!child || this.destroyed || child===this)return child; addResizeListener(child); return origiAddChildAt.call(this, child, index); } let origiRemoveChildAt = o.removeChildAt; o.removeChildAt = function(index:number):Node{ removeResizeListener(this.getChildAt(index)); return origiRemoveChildAt.call(this, index); } for(let i = 0; i < o.numChildren; i++) { let child = o.getChildAt(i); if(child != this._backgroundImg) { addResizeListener(child); } } this._refreshSize(); } measureWidth():number{ var max=0; let o:Sprite = this.owner as Sprite; for (var i=o.numChildren-1;i >-1;i--){ var comp = o.getChildAt(i) as Sprite; if (comp.visible && comp != this._backgroundImg){ max=Math.max(comp._x+comp.width *comp.scaleX,max); } } return max; } measureHeight():number{ var max=0; let o:Sprite = this.owner as Sprite; for (var i=o.numChildren-1;i >-1;i--){ var comp = o.getChildAt(i) as Sprite; if (comp.visible && comp != this._backgroundImg){ max=Math.max(comp._y+comp.height *comp.scaleY,max); } } return max; } private _prepareToRefresh(){ let o:UIComponent = this.owner as UIComponent; if(o)o.callLater(this._refreshSize.bind(this)); } private _refreshSize(){ let o:UIComponent = this.owner as UIComponent; o.width = this.measureWidth() + this._paddingRight; o.height = this.measureHeight() + this._paddingBottom; } /** @prop {name:paddingBottom, tips:"设置下边距", type:number} */ get paddingBottom() { return this._paddingBottom; } set paddingBottom(v:number) { if(this._paddingBottom != v){ this._paddingBottom = v; this._prepareToRefresh(); } } /** @prop {name:paddingRight, tips:"设置右边距", type:number} */ get paddingRight() { return this._paddingRight; } set paddingRight(v:number) { if(this._paddingRight != v){ this._paddingRight = v; this._prepareToRefresh(); } } }