我创建了一个包含两个不同部分的 UIViewController
。有一个 headerView
和一个 contentView
,我想在其中添加一个 WKWebView
实例。
由于我以编程方式创建WKWebView
,因此我必须以同样的方式添加约束。
这是我添加它们的方法:
-(void)loadYoutubeVideoWithID:(NSString *)videoID {
if (![self webView]){
/* Create WebView */
WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height)];
/* Set Delegate */
[webView setNavigationDelegate:self];
/* Set Local Property */
[self setWebView:webView];
/* Add to content view */
[self.contentView addSubview:webView];
/* Create Constraints */
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[webView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[webView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]];
}
}
尽管添加了约束,但我无法让它们得到尊重。我已经根据 StackExchange 中的其他答案尝试了这些约束的四种不同变体,但我的 WKWebView
在屏幕旋转时从不调整大小。
我不确定如何解决这个问题。我有链接的输出日志 here (它相当长)关于打破约束,但它对我没有多大用处。
有谁知道为什么我无法调整 WKWebView
的大小?
感谢您的宝贵时间。
编辑:当使用常规 UIImageView 代替 WKWebView 时,也会发生这种情况
最佳答案
解决这个问题相当简单。它要求您添加以下行:
[webView setTranslatesAutoresizingMaskIntoConstraints:NO];
在初始化您的 WKWebView
实例或您希望在内容 View 中调整大小的任何其他 UIView
之后。这是固定的例子:
-(void)loadYoutubeVideoWithID:(NSString *)videoID {
if (![self webView]){
/* Create WebView */
WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height)];
/* Ensure Constraints remain when resizing the View */
[webView setTranslatesAutoresizingMaskIntoConstraints:NO];
/* Set Delegate */
[webView setNavigationDelegate:self];
/* Set Local Property */
[self setWebView:webView];
/* Add to content view */
[self.contentView addSubview:webView];
/* Create Constraints */
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[webView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[webView]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(webView)]];
}
}
我希望其他人发现这个指导。
关于ios - WKWebView 不断打破约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681998/