Auto Layout view to fullscreen on rotate

落爺英雄遲暮 提交于 2019-12-08 05:30:13

问题


I am writing a video playing app. The app has information about the app below the video while watching in portrait mode, but when the app is turned to landscape I want the video to go full screen. Unfortunately when the app is turned to landscape the bottom view constrains the video view from expanding all the way from the top to the bottom even though I've turned the height constraint to priority == 1.

Portrait Mode:

Landscape Mode:

I've tried hiding the lower view, but that throws the whole layout out of whack when I show the view on rotating back to portrait because hiding the view destroys the constraints associated with the view.

Is there a way I can make a single view take up the entire screen easily and revert back to the way things were easily with Auto Layout?

Thank you.


回答1:


Yes, there is an easy way, but you need to do a little math. You can relate the height of your video view to the superview, using the multiplier and constant properties. You can have two equations defining what you want, and solve for the variables. For example, say you want your height to be 225 in portrait (in a 568 point high screen), and full height, 320, in landscape. That gives you these two equations (in words, the equation says, "I want my height to equal self.view's height times a multiplier plus a constant"):

225 = 568m + constant and 320 = 320m + constant

If you solve these two equations, you get -0.3831 for m and 442.6 for the constant. So, in IB, you should give your video view a height constraint, and make an IBOutlet to it. The other views could also have height constraints (but there are probably other ways), but the important point is you want them to have vertical spacing constraints to each other so they're tied together, and no constraint to the bottom of the view. That way, when the video view expands, it will push those other two views off the screen. In code, you would do this:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.topView removeConstraint:self.heightCon];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topView attribute:NSLayoutAttributeHeight relatedBy:0 toItem:self.view attribute:NSLayoutAttributeHeight multiplier:-.3831 constant:442.6]];
}

heightCon is my outlet to topView's (your video view) height constraint. We remove that, and then replace it with one in self.view that relates the two heights properly. If you're supporting both screen sizes, you would have to solve the equations using 480 instead of 568 in that first equation, and add the correct constraint based on the device. There's no need to do anything on rotation, the constraint system handles that automatically.



来源:https://stackoverflow.com/questions/20087254/auto-layout-view-to-fullscreen-on-rotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!