简体   繁体   English

以编程方式处理旋转和调整视图(Xcode)

[英]Handling rotation and adjusting views programmatically (Xcode)

Here is the problem I've been struggling with: 这是我一直在努力的问题:

I'm creating a view programatically using loadView. 我正在使用loadView以编程方式创建view Once it's loaded it looks just great in Portrait view. 加载后,在“人像”视图中看起来非常不错。 However, I want to handle rotation of the device. 但是,我想处理设备的旋转。 Therefore I use willAnimateRotationToInterfaceOrientation method. 因此,我将使用willAnimateRotationToInterfaceOrientation方法。

Within this method I call a function that adjust all the elements. 在此方法中,我调用一个可调整所有元素的函数。 What that function does is just goes through all my views and sets new CGRect to each of them. 该功能的作用只是遍历我的所有视图,并为每个视图设置新的CGRect It works just fine on portrait orientations (up and upside-down), but once I change orientation to horizontal, it crops. 它在纵向方向(上下颠倒)上都可以正常工作,但是一旦将方向更改为水平方向,它就会进行裁剪。

Two questions: 两个问题:

  1. What is the most likely reason for such behavior? 发生这种行为的最可能原因是什么?
  2. How would you suggest handling device rotation without creating a separate view for horisontal / vertical orientations? 您将如何建议在不为水平/垂直方向创建单独视图的情况下处理设备旋转?

I think you are missing the key part. 我认为您缺少关键部分。 When you are setting the frame at portrait view at view did load, view got the frame but when it change to the landscape it change but again from there i think you are not setting the frame for portrait view. 当您在纵向视图上设置框架时,视图确实加载了,视图得到了框架,但是当它变为横向时,它改变了,但是从那里再次出现,我认为您没有为纵向视图设置框架。 use notification 使用通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];


-(void) orientationChanged:(NSNotification *)notification
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        UIDeviceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

        if((orientation == UIDeviceOrientationPortrait) || (orientation == UIDeviceOrientationPortraitUpsideDown)) {
           // set frame here
        }else if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)){
          // set frame here too
        }
    }];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM