viewWillTransitionToSize为我们提供了一个大小和一个transitionocordinator。如果我的视图将要旋转,我想找到什么样的元素将是后旋转,所以我可以调整之前的值,以适合新的旋转大小。
我能从transitioncordinator中获得对旋转视图控制器的引用吗?我知道它有viewControllerForKey:但我不知道钥匙是什么。
它通过的大小只是viewController.view的大小,这不够有用。我需要能够问什么大小的标签将在旋转后。

最佳答案

我假设您使用的是auto-layout或其他一些使了解ui元素的最终大小变得非常重要的东西。
我不相信您的视图在调用viewWillTransitionToSize时调整了大小,因此没有发生布局。
您需要做的是强制自己调整大小,测量ui元素,然后将视图调整回其原始大小(以便在旋转时可以将其设置为新大小)。
在这种情况下,假设您想知道名为UILabel_myLabel

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    // _myLabel is the label we want to measure
    // This prints out its size pre-rotation:

    NSLog(@"Label size: %f, %f", _myLabel.bounds.size.width, _myLabel.bounds.size.height);

    CGRect oldFrame = self.view.frame;

    //Force this view controller's view to take on the
    // new size and re-layout immediately

    self.view.frame = CGRectMake(0, 0, size.width, size.height);
    [self.view setNeedsUpdateConstraints];
    [self.view setNeedsLayout];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];

    // _myLabel's size will now be the value it would take on post-rotation:

    NSLog(@"Label size (after rotation): %f, %f", _myLabel.bounds.size.width, _myLabel.bounds.size.height);

    //Restore the view so it can animate into the new size normally

    self.view.frame = oldFrame;
    [self.view setNeedsUpdateConstraints];
    [self.view setNeedsLayout];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
}

这对你的问题是一个很难的解决办法。如果你能想出一种方法来独立计算你需要测量的东西的布局,那就更好了(尽管我知道这可能太复杂了)。

10-07 19:49
查看更多