问题
I have this problem, i am moving a 'A' View on screen wherever user want's to move (Which is added from storyboard), i am moving View using event-handling methods and that is working fine,
What problem i have now is, when i add new 'B' View (Programatically) to ViewControllers view, my 'A' View which i have moved to some other position, moves automatically to its default position. (At the position where it is on storyboard).
So i think, i have figured out the reason that whenever we add new view to the view hierarchy viewWillLayoutSubViews: get's call and its reposition the views to their default. So i want to know that how can i prevent this?
See below image for more details:
Note:
Both A and B (Orange and Red are UIView)
Orange view is added from storyboard and red view is added programatically.
Also see my previous question about the similar kind problem,
Any help would be appreciated.
回答1:
If you are using autoLayout, you must add constraints for all the views in the scene.
Since you are not adding any constraints for the view A, the system will add constraints internally to place the view at that specific position. If you then move the view manually using frames, this will not hold as the constraints will force the view to move to its original position.
You can approach this problem in two ways:
- Manually add constraints to all views in the scene, whether it is in storyboard or added programatically. Each constraint has a
constantattribute. Change the value of thisconstantif you need to resize or reposition the view. - Disable autolayout altogether from the scene. You may then reposition or resize views by changing frame.
Hope this helps! :)
回答2:
Yesterday I experienced same problem. If you change the position of view (A in your example) runtime created in xib or storyboard with Autolayout constraints, then add some control to same subview, view A will be positioned to original constraints.
There are 2 solutions as far as I found:
viewA.translatesAutoresizingMaskIntoConstraints = YES;after initialising viewA- Create your viewA programatically without constraints.
来源:https://stackoverflow.com/questions/35883784/view-on-screen-resizing-and-repositioning-itself-when-new-view-is-added-into-hie