[英]Simple way to redraw view programatically when device orientation changes
我是iOS开发的新手,我的任务是在设备方向改变时以编程方式更改ViewController的更新。 我在这里找到了一个答案的片段,但没有完成任务。
我尝试将其添加到我的View Controller的viewWillLayoutSubviews
中,但是得到的只是一个未使用的变量警告。
CGRect rotatedFrame = [self.view convertRect:self.view.frame fromView:self.view.superview];
作为“提示”,有人告诉我在viewWillLayoutSubviews
实现很简单。 遍历和更改我的VC中的所有CGRect听起来并不像几行代码。 必须有一种更简单,更有效的方法来执行此操作,但是我只在该站点上发现了解决方案的摘要。 谢谢阅读。
您正在使用的代码行是将CGRect
分配给rotatedFrame变量,它不会更新视图控制器上的任何内容。
有很多方法可以解决此问题,但这取决于视图中包含的内容以及配置方式。 例如,诸如Auto Layout
之类的事情可以让您在Interface Builder中配置几乎所有内容,并避免执行代码中的大多数事情。
您的任务是以编程方式执行此任务,因为我们知道每次旋转设备时都会调用viewWillLayoutSubviews
因此这是一个不错的起点。 这是我采用转换方式旋转视频以适应新方向的一种懒惰方式:
//Vertical
CGSize size = self.view.frame.size;
someView.transform = CGAffineTransformMakeRotation((M_PI * (0) / 180.0))
someView.frame = CGRectMake(0, 0, MIN(size.width, size.height), MAX(size.width, size.height));
//Horizontal
CGSize size = [UIScreen mainScreen].bounds.size;
int directionModifier = ([UIDevice currentDevice].orientation == UIInterfaceOrientationLandscapeLeft) ? -1 : 1;
someView.bounds = CGRectMake(0, 0, MAX(size.width, size.height), MIN(size.width, size.height));
someView.transform = CGAffineTransformMakeRotation((M_PI * (90) / 180.0) *directionModifier);
someView.transform = CGAffineTransformTranslate(someView.transform,0,0);
您的视图中有多少个子视图? 他们分组了吗? 如果您使用的是自动调整大小的蒙版,则可能仅需调整一个或两个视图的帧即可。 如果您的根视图包含许多子视图,则可以遍历需要进行类似调整的视图,从而不必编写过多的代码。 这实际上取决于如何设置所有内容。
我想出了如何确定viewWidth和viewHeight并将它们设置为CGFloats的方法。 然后,我添加了一条if-else语句,该语句确定显示是纵向还是横向,并相应地设置有问题的calculateButton。
为冗长的代码而道歉,但是我在搜索该网站时发现答案的“摘要”,但是对于iOS来说,它是新手,很难弄清楚该怎么做。 希望这对以后的人有所帮助。 (希望它是正确的)
- (void) viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
CGFloat viewWidth = self.view.bounds.size.width;
CGFloat viewHeight = self.view.bounds.size.height;
CGFloat padding = 20;
CGFloat itemWidth = viewWidth - padding - padding;
CGFloat itemHeight = 44;
// Bunch of setup code for layout items
// HOMEWORK: created if-else statement to deal w/ portrait vs. landscape placement of calculateButton.
if (viewWidth > viewHeight) {
// portrait
CGFloat bottomOfLabel = viewHeight;
self.calculateButton.frame = CGRectMake(padding, bottomOfLabel - itemHeight, itemWidth, itemHeight);
} else {
// landscape
CGFloat bottomOfLabel = CGRectGetMaxY(self.resultLabel.frame);
self.calculateButton.frame = CGRectMake(padding, bottomOfLabel + padding, itemWidth, itemHeight);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.