无法更新viewDidLoad中的view.layer.frame? [英] cannot update view.layer.frame in viewDidLoad?
问题描述
我试图在我的单个视图控制器项目的viewDidLoad方法中执行以下代码:
self.view.layer.frame = CGRectInset(self.view.layer.frame,20,20);
但是它没有提供所需的插图.但是我用相同方法进行的其他UI更改也可以正常工作,例如
self.view.layer.backgroundColor = [UIColor orangeColor] .CGColor;
上面的代码确实有效,并且背景变为橙色,但框架无效.
仅当我将代码行放在viewDidAppear中时,插入项才起作用.如果有人可以解释,我想了解这种行为的主要原因.预先谢谢你.
viewDidLoad
方法为时过早,无法设置视图的框架,因为其他原因稍后会更改框架.
例如,如果这是您的根视图控制器,则 UIWindow
对象将在将视图作为子视图添加到自身时设置视图的框架. viewDidLoad
方法在 loadView
返回后立即运行,然后任何外部对象(例如 UIWindow
)都可以在视图上动手.>
您可以通过使用自定义视图(如果尚未使用)并在自定义视图类中覆盖 setFrame:
来进行测试:
-(void)setFrame:(CGRect)frame {[super setFrame:frame];}
在该方法中放置一个断点,您将看到在 viewDidLoad
返回后的某个时间设置视图的框架.
I am trying to execute following code in viewDidLoad method of my single view controller project:
self.view.layer.frame = CGRectInset(self.view.layer.frame, 20, 20);
But it does not give the desired inset. However other UI changes i make in the same method do work e.g
self.view.layer.backgroundColor = [UIColor orangeColor].CGColor;
Above line of code does work and background is change to orange but the frame does not.
The inset works only if I place the line of code in viewDidAppear. I would like to understand the key reason for this behavior if anyone can explain. Thank you in advance.
The viewDidLoad
method is too early to set your view's frame because something else is changing the frame later.
For example, if this is your root view controller, then the UIWindow
object will set the view's frame when it adds the view to itself as a subview. The viewDidLoad
method runs as soon as loadView
returns, before any outside object (like the UIWindow
) can get its hands on the view.
You can test this by using a custom view (if you're not already) and overriding setFrame:
in the custom view class:
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
}
Put a breakpoint in that method and you'll see that the view's frame gets set some time after viewDidLoad
returns.
这篇关于无法更新viewDidLoad中的view.layer.frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!