ios - WKWebView 不断打破约束?

标签 ios objective-c iphone autolayout

我创建了一个包含两个不同部分的 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 在屏幕旋转时从不调整大小。

Before

After

我不确定如何解决这个问题。我有链接的输出日志 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/

相关文章:

ios - UITableView 方法被 TableView 大小覆盖

objective-c - 如何将原始字节写入 NSMutableData 对象?

iphone - 在 MKMapView 上获取用户当前位置

ios - 将 UIWebView 转换为具有动态大小的 UITableViewCell

ios - 在 TableView 的所有行中查找所有执行函数,而不是可见单元格

ios - 将多个 CoreData 数据库动态合并为一个虚拟的单一数据库

objective-c - 封装特定类型画笔在Objective-C中的绘制方式

iphone - iOS 上的页面 curl

objective-c - 选择器 OpenDevice 的未知类方法

iphone - 改变 CAShapeLayer 中的线宽