为什么在viewDidLoad中添加子视图不起作用

use*_*002 2 objective-c uiwebview viewdidload viewwillappear ios

我试图将UIToolBar添加到UIWebView中,但每当我在viewDidLoad中插入此代码时UIToolBar都没有显示,但是当在viewWillAppear中完成时,它可以工作.有人可以向我解释一下.

-(void)viewDidLoad
{
[super viewDidLoad];
self.forwardButton = [[UIBarButtonItem alloc]initWithTitle:@"Forward"          style:UIBarButtonItemStylePlain target:self action:@selector(forward)];
self.backButton = [[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
NSArray *buttonsArray = @[self.backButton,self.forwardButton];
CGRect toolBarFrame = CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44);
self.toolbar = [[UIToolbar alloc]initWithFrame:toolBarFrame];
[self.toolbar setItems:buttonsArray animated:YES];
[self.toolbar sizeToFit];
[self.view addSubview:self.toolbar];
}
Run Code Online (Sandbox Code Playgroud)

Sas*_*ats 5

添加子视图viewDidLoad,但将其设置frameviewWillAppear.self.view.frame正在被viewWillAppearUIKit调用之前正在设置.您获得的值viewDidLoad是在nib中设置的值,通常与实际值不同frame.

不要忘记设置autoresizingMask或使用自动布局.

  • UIKit在`viewWillAppear:'之前设置了正确的尺寸,意味着将设置`frame`,`bounds`和`center`.所有这些属性都由相应的`CALayer`的相同属性支持,因此,除非设置`transform`,否则你应该期望"frame"和"bounds"在"正确性"方面的行为相似.希望它有意义. (2认同)