WKWebView约束不起作用

我只是想把WKWebView固定在self.view的各个方面,这样无论旋转,它都会尽可能的伸展。 使用下面的代码,无论初始旋转是什么,它都将填充视图,但旋转后,它完全消失:

-(void)viewWillAppear:(BOOL)animated { [super viewDidLoad]; self.title = @"Worship Slides"; self.productURL = @"http://www.316apps.com/Fritch/worship.key"; NSURL *url = [NSURL URLWithString:self.productURL]; NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]; _theWorship = [[WKWebView alloc] initWithFrame:self.view.frame]; [_theWorship setTranslatesAutoresizingMaskIntoConstraints:NO]; [_theWorship loadRequest:request]; _theWorship.frame = CGRectMake(0, 0, self.navigationController.view.bounds.size.width, self.navigationController.view.bounds.size.height); [self.view addSubview:_theWorship]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_theWorship attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.bottomLayoutGuide attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_theWorship attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_theWorship attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_theWorship attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]]; } 

 -(void)viewWillAppear:(BOOL)animated { **[super viewDidLoad];** 

改成:

 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; 

还要确保你添加了一个方法来检查你的代码是否已经被调用,否则它会被多次调用/每次该视图将会出现。 你应该改用viewDidLoad方法来调用它,但是只要你不多次调用它,你可以select它。

另外,添加所有可以调用的内容之后:

 [_theWorship layoutIfNeeded]; 

摆脱addConstraint并调用isActive = true。 请参阅文档:

在为iOS 8.0或更高版本开发时,将约束的活动属性设置为true,而不是直接调用addConstraint(_ :)方法。 isActive属性自动添加并从正确的视图中删除约束。

或者使用NSLayoutAnchor ; 它不像NSLayoutConstraint那么长时间。 我只在循环中使用NSLayoutConstraint,或者当我不能用NSLayoutAnchor(即中心乘)表示约束时。