0

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?

jdog
  • 10,351
  • 29
  • 90
  • 165

1 Answers1

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];
}
Yogesh Maheshwari
  • 1,324
  • 2
  • 16
  • 37
  • But in layoutSubviews how do I know if I should layout for landscape or portrait? L=CGRectMake(35, 759, 380, 72) P=CGRectMake(235, 49, 60, 12) – jdog Oct 04 '12 at 15:06
  • you can keep one variable in CustomView for orientation and set that variable in "willRotateToInterfaceOrientation" method before calling setNeedsLayout – Yogesh Maheshwari Oct 05 '12 at 05:08
  • I would rather not set the views layout mode from the viewController, but have the view controller just do it on its own when the layout mode changes. Tried to get the layout via the following but it doesn't work UIInterfaceOrientationIsLandscape([[UIDevice currentDevice] orientation]) – jdog Oct 10 '12 at 16:27
  • There is one problem in doing anything like that.. your ViewController can stay in portait even when your device is in landscape and your view should have the same orientation as of ViewController – Yogesh Maheshwari Oct 11 '12 at 07:31