Example project:
https://github.com/Sylvia-YiyinShen/AdaptiveLayoutExample
This 2 minutes tutorial covers two ways of making adaptive layout for iPhone and iPad
Requirement:
Make a UIView to have fixed left/right margin on iPhone and make it with fixed width on iPad
Solution 1 - Dynamic width:
Dynamically update the width constraint. Just set width on iPad. On iPhone, calculate the viewWidth = screenWidth - 2 * margin
1. Link the widthConstraint from storyboard/nib to viewController
2. Configure widthConstraint as below in viewDidLoad
Solution 2 - Trait Variations
1. Select the viewController in storyboard/nib. ensure 'Use Trait Variations' in File Inspector has been selected
2. Configure the UIView for iPhone
Tap the 'View as XXX' at the bottom, select an iPhone device, then tap 'Vary for Traits', choose width and height in this case.
The menu bar will turn blue. Do not tap 'Done Varying' at this moment.
Select the UIView and give the necessary constraints for iPhone. (E.g. Height, Top Space, Trailing and Leading)
Tap 'Done Varying'. Now we've done the configuration for iPhone
3. Configure the UIView for iPad
Tap the 'View as XXX' at the bottom, select an iPad device then tap 'Vary for Traits', choose width and height in this case.
Select the UIView and check the existing constraint in Size Inspector. If you did step 2 correctly, the constraint set for iPhone should not be visible.
Now give the necessary constraints for iPad. (E.g. Height, Top Space, Width and Horizontally-centered)
Tap 'Done Varying'. Now we've done the configuration for iPad
Run the example project, the above solutions should work exactly the same on iPhone or iPad.
We can leave the viewController file untouched via Solution 2. However, if the left/right margin relies on other constraint or component, solution 1 seems to be the only choice.
No comments:
Post a Comment