How to create a UIView for both portrait and lands

2019-08-28 04:01发布

问题:

I am trying to create a UIView that will work for both portrait and landscape mode, but not sure how to achieve this. FYI - I am laying out all the components via code so no XIB or Storyboard... this is a requirement.

I have a method called createView that lays out all the view components (buttons, labels, etc...) which I call any time the view is created.

What I don't know is say my controller adds the view via addSubview:myNewCustomView while in horizontal mode, then how do I change the layout of the components in my custom UIView when switching from portrait to landscape?

Would I create to methods in my custom UIView one to layout for portrait and another for landscape? If i have two methods, would I have to get the parents display mode, landscape or portrait, then call the appropriate createView method in my custom UIView?

回答1:

You can over-ride layoutSubviews method in your CustomView Class. And in your ViewController call setNeedsLayout on your CustomView Object. Keep a variable for orientation in your CustomView

In CustomView:-

- (void) layoutSubviews(){
    // set position and height width of the subviews according to this views params
}

In YourViewController:-

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
    [yourCustomViewObj setOrientation:orientation];
    [yourCustomViewObj setNeedsLayout];
}