WKWebView约束不起作用

时间:2017-01-31 18:26:09

标签: ios objective-c 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]];
}

2 个答案:

答案 0 :(得分:1)

取消addConstraint并调用isActive = true。请参阅文档:

When developing for iOS 8.0 or later, set the constraint’s active property to true instead of calling the addConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view.

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

答案 1 :(得分:0)

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

更改为:

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

还要确保添加一个方法来检查您的代码是否已被调用,否则每次出现视图时都会多次调用它。您应该改为从viewDidLoad方法调用它,但只要您不多次调用它就可以选择它。

此外,添加完所有内容后,您可以致电:

[_theWorship layoutIfNeeded];