【问题标题】:Overriding layoutSubviews when rotating UIView旋转 UIView 时覆盖 layoutSubviews
【发布时间】:2010-10-29 11:43:00
【问题描述】:
在 UIView 内旋转滚动视图时,滚动视图无法使用其默认的自动调整大小行为正确定位。
因此,当发生旋转时,在willRotateToInterfaceOrientation 中我调用[self.view setNeedsLayout]; 并且我的layoutSubviews 方法如下:
- (void)layoutSubviews {
NSLog(@"here in layoutSubviews");
}
但是在方法上放了一个断点,它似乎永远不会进入方法。
我需要做其他事情才能让它工作吗?
谢谢。
【问题讨论】:
标签:
iphone
objective-c
uiview
ios4
layoutsubviews
【解决方案1】:
willRotateToInterfaceOrientation 在方向改变之前被调用,因此你的 UIView 仍然有旧的大小。
尝试改用 didRotateFromInterfaceOrientation。
另外,为了增加效果,我会在 willRotateToInterfaceOrientation 中隐藏 scrollView(可能在 UIAnimation 块内),调整它的大小,然后在 didRotateFromInterfaceOrientation 中显示它(同样,可能在动画块内)。
这是来自我的一个应用程序的 sn-p:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = YES;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = NO;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}
您甚至可以通过使用 UIInterfaceOrientationIsPortrait(orientation) 或 UIInterfaceOrientationIsLandscape(orientation) 检查新方向来做一些花哨的事情。
【解决方案2】:
如果视图没有调整大小或移动,调用[someScrollView setNeedsLayout] 可能实际上不会做任何事情。正如您所说,永远不会使用默认的自动调整大小行为调用该方法,因为默认行为是根本不调整大小。您很可能需要设置someScrollView.autoresizingMask。当界面旋转时,视图会自行调整大小,并调用layoutSubviews。
【解决方案3】:
该方法没有被调用,因为 ViewController 没有 layoutSubviews 方法。
当您调用[self.view setNeedsLayout]; 时,它只会调用视图控制器视图的layoutSubviews 方法:[self.view layoutSubviews]。
您需要子类化 UIScrollview 才能完成这项工作。
【解决方案4】:
实际上,您可能想要覆盖视图控制器 willAnimateRotationToInterfaceOrientation:duration: 方法(摘自我的示例):
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration {
if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) {
boardView.frame = CGRectMake(0, 0, 320, 320);
buttonsView.frame = CGRectMake(0, 320, 320, 140);
} else {
boardView.frame = CGRectMake(0, 0, 300, 300);
buttonsView.frame = CGRectMake(300, 0, 180, 300);
}
}
【解决方案5】:
您应该覆盖 willAnimate... 并设置您的视图的新框架。 Layoutsubviews 应该在旋转过程中自动调用。