How to create a UIView for both portrait and lands

2019-08-28 04:21发布

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条回答
疯言疯语
2楼-- · 2019-08-28 04:37

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];
}
查看更多
登录 后发表回答