问题描述
使用Xcode 4.2/iOS5.0
Using Xcode 4.2/iOS5.0
我有一个viewController和一个关联的viewController.xib.viewController被设置为.xib文件的所有者.它是从 UINavigationController
调用的.
I have a viewController and an associated viewController.xib. The viewController is set up as the .xib's file's owner. It is invoked from a UINavigationController
.
当设备旋转纵向/横向时,我正在尝试一些手动布局
I am attempting some manual layout when the device is rotated portrait/landscape
据我了解,要覆盖的 UIView
方法是
As I understand it the UIView
method to override is
- (void)layoutSubviews;
这是您进行布局的地方
但是-与 drawRect
一样,您不会直接调用它,它会在iOS适当的时候被调用
But - as with drawRect
- you do not call this directly, it is invoked when appropriate by iOS
相反,您调用 setNeedsLayout
...
Instead you call setNeedsLayout
...
所以我在ViewController中有这个
So I have this in the ViewController
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)
fromInterfaceOrientation {
[[self view] setNeedsLayout];
}
在同一个ViewController中,我有这个
and in the same ViewController I have this
- (void)layoutSubviews {
//.manual override of automatic layout on rotation
NSLog(@"layoutSubviews");
}
但是 layoutSubviews
没有被调用,我也不明白为什么.
However layoutSubviews
does not get called and I don't understand why.
这是一个线索...如果我直接将 layoutSubviews
称为 [self layoutSubviews]
Here is a clue... If I call layoutSubviews
directly as [self layoutSubviews]
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)
fromInterfaceOrientation {
[self layoutSubviews];
}
它会触发
但是,如果我将其称为 [[self view] layoutSubviews]
,则不会
But if I call it as [[self view] layoutSubviews]
it does not
因此,视图及其控制器似乎未正确连接吗?
So it appears that the view and it's controller are not wired up correctly?
推荐答案
您的问题是,您已在视图控制器上而非视图上实现了 -layoutSubviews
.永远不会这样称呼它. -layoutSubviews
是一种机制,通过该机制,自定义视图可以布局其自己的子视图(例如,具有图像的 UIImageView
的 UIButton
标签使用 UILabel
,并使用 -layoutSubviews
确保图像视图和标签均正确放置).这不是视图控制器可以控制其视图布局的机制.
Your problem here is you've implemented -layoutSubviews
on your view controller, instead of on your view. It will never be called this way. -layoutSubviews
is a mechanism by which a custom view can lay out its own subviews (e.g. a UIButton
that has a UIImageView
for the image and a UILabel
for the label, and uses -layoutSubviews
to ensure the imageview and label are all positioned correctly). It's not a mechanism by which a view controller can control the layout of its views.
如果要更改旋转的布局,则应该继续在 -didRotateFromInterfaceOrientation:
内设置新的布局.
If you want to change layout on rotation, then you should just go ahead and set up the new layout inside of -didRotateFromInterfaceOrientation:
.
这篇关于UIView layoutSubviews没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!