旋转横向和背面时调整 UIView 大小的最佳方法

Best method to resize UIView when rotated to landscape and back

由于我是 ios 编程的新手,所以我有更多的一般设计问题。 我有一个 ViewController,其中包含一个工作正常的 GraphView (UIScrollView + UIView)。当我旋转到横向时,我希望 GraphView 将其高度调整为显示高度(因此它会填满整个屏幕),但在纵向时只有 300pts。

到目前为止我所做的是在 ViewController 中实现 viewWillLayoutSubviews 并重置约束:

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

并在 GraphView.m 中:

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

(因为我需要代码中的变量kGraphHeight来绘制Graph)。这似乎不是一个非常优雅的解决方案,所以我想问问更好的方法是什么?非常感谢您的投入:)

在GraphView.m

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

updateViewDimensions方法将设置UIScrollView和UIView的框架

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

将视图旋转到横向后 viewDidLayoutSubviews 将被调用。

它对我有用。