Deep understanding of layout parameter of cocos2d-x

Time:2020-11-17

Before the understanding is not deep, today encountered a pit, harvest some deeper understanding.

The requirements are as follows: a relatively layout panel with an ImageView, and several buttons in other parts of the interface. After pressing down, the position of this ImageView needs to be changed dynamically.

According to the usual understanding, after the button event is triggered, it can only be done in this way:

node:getLayoutParameter():setMargin({ left = 10, right = 0, top = 0, bottom = 0 })

However, this sentence actually did not work! Move this sentence to the pile of code when the UI is created, but it works again! Curious, so I fell into this pit.

Later, I didn’t know how my brain was inspired. I saw one in the layout classrequestDoLayout()Method, so the code is changed to this, and finally takes effect:

node:getLayoutParameter():setMargin({ left = 10, right = 0, top = 0, bottom = 0 })
node:getParent():requestDoLayout()

My understanding is that in a relatively positioned panel, if it is during UI creation (i.e. at the first frame), no matter how the child nodes in the panel are handled, they will take effect and do not need to be executed manuallyrequestDoLayout()Method to request the relocation of the panel, because the panel is in the onEnter state and the internal state is dirty. After the UI has been created (that is, the first frame is completed), it is necessary to change the position of the child nodes in the panel at this time. The panel will not be aware of the change
, the internal state is not dirty, and the child node will not be relocated, so it needs to be requested once manuallyrequestDoLayout()To make the new settings of the panel take effect.

An interesting experiment is as follows: create a panel, relative positioning, create an ImageView sub node node, align left and align top (as long as it is not centered, because it will be fixed after it is set to be in the middle). After creating it, casually find a button a to do an event, and write as follows:

node:setPositionX(100)

Click the button to trigger the event, and you will find that the location of the node has changed. Then add a button B to trigger the event

node:getParent():requestDoLayout()

First click button a, the node position changes, and then click button B, you will find that node runs back to the original position again, ha ha.

Conclusion: to use the program to change the position dynamically in the relative positioning panel, avoid usingsetPosition()You still need to use the setmargin() method of layoutparameter, but you have to do it again for the panelrequestDoLayout()Call to notify the panel to comb the child nodes again