Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

ios - XCode: How to change layout of views between landscape and portrait mode

In portrait mode I have four views on top of one another from the top to the bottom of the view controller (see image).

portrait view

I then want to change the position of the views relative to one another when the device transitions to landscape (see image two).landscape view

I want view 4 to move alongside views 2 and 3 and them all the sit below view 1.

Some of the layout conditions:

  • view 1 is attached to the top of the view controller in both landscape and portrait.
  • view 4 is attached to the left, right and bottom margins of the view controller in portrait mode.
  • Views 2, 3 & 4 are centered horizontally within the portrait view.

What is the best method to achieve the different layouts?

Would the most elegant solution be to make a reference to the constraints in the view controllers code and activate and deactivate them in viewWillTransition? Or is there a way to use vary for traits to achieve this (I can imagine views 2, 3 & 4 being centered horizontally would make this hard to achieve, as well as adding the new constraints for view 4 in landscape mode)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We used to set up different sets of constraints and activate/deactivate them based upon orientation change. But nowadays can use size classes and "vary for traits".

For example, I start with a simple view and choose a compact width size class and then choose "Vary for traits":

enter image description here

I then add the appropriate constraints and click on "Done varying":

enter image description here

I then choose a "regular width size class" and repeat the process ("Vary for traits", add the constraints, click on "Done varying":

enter image description here

You then end up with a scene that will have a completely different set of constraints active for compact width size classes and regular width size classes. I.e. when I run the app, if the device rotates, the new constraints are activated:

enter image description here

For more information, see WWDC 2016 videos on adaptive layouts:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...