Kathiieee
Kathiieee

Reputation: 211

Best method to resize UIView when rotated to landscape and back

Since I am very new to ios programming I have more of a general-design question. I have a ViewController which contains a GraphView (UIScrollView + UIView) which works fine. When I am rotating to landscape I want the GraphView to resize its height to the display height (so it fills the whole screen) but only 300pts when in portrait.

What I did so far is implementing viewWillLayoutSubviews in the ViewController and resetting the constraints:

- (void)viewWillLayoutSubviews{        
_graphViewHeightConstraint.constant = ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) ? 300:[[UIScreen mainScreen] bounds].size.height-self.navigationController.navigationBar.frame.size.height - 2*_distanceToTopView.constant; 
}

and in GraphView.m:

- (void)layoutSubviews{
kGraphHeight = self.frame.size.height;
[self setNeedsDisplay];  
}

(because I need the variable kGraphHeight in the code to draw the Graph). This does not seem like a very elegant solution so I wanted to ask what the better way would be? Many thanks for your inputs :)

Upvotes: 3

Views: 1038

Answers (1)

Haripal Wagh
Haripal Wagh

Reputation: 572

In GraphView.m

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews]; 
    kViewWidth = <GET_SCREEN_WIDTH_HERE>;
    kViewHeight = <GET_SCREEN_HEIGHT_HERE>;
    [self updateViewDimensions];
}

and updateViewDimensions method will set the frame of UIScrollView and UIView

- (void)updateViewDimensions
{
    scrollView.frame = self.view.frame;
    yourView.frame = CGRectMake(kViewXStartsFrom, kViewYStartsFrom, kViewWidth, kViewHeight);
}

after rotating view to Landscape viewDidLayoutSubviews will be called.

It's working for me.

Upvotes: 2

Related Questions