WKWebView 在旧项目中显示内容错误的框架

WKWebView show content wrong frame in old project

我有一个旧的 iOS 项目使用 Objective C。当我将 WKWebView 添加到 ViewController

    NSURL *url = [NSURL URLWithString:@"https://www.google.com"];

    WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];

    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:theConfiguration];
    [self.view addSubview:_webView];
    
    self.webView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        
                                             [self.webView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
                                             [self.webView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
                                             [self.webView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
                                             [self.webView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor]
    ]];

    [_webView loadRequest:[NSURLRequest requestWithURL:url]];

如果我通过 Xcode 和 iOS 14 安装应用程序,webview 工作正常,但在我断开连接 Xcode 并直接打开应用程序后,webview 显示错误框架的内容。如果我通过 Xcode 在 iOS 12.5 中构建应用程序,Web 视图也会显示错误框架的内容。 如果我从 Xcode 12.5 创建新项目,并使用相同的代码,它工作正常。

这是通过 Xcode build

打开应用程序时的屏幕截图

https://i.stack.imgur.com/rYb3M.png

这是直接打开应用程序时的屏幕截图:

https://i.stack.imgur.com/4q0uD.png

几点观察 -

  1. 此代码混合使用了 _webViewself.webView。为清楚起见,您至少应统一此代码块的用法。

  2. 你到底在哪里调用这部分? viewDidLoad() 还是在某个事件之后?你可以在添加这个之后尝试添加一个 layoutIfNeeded() 调用吗?

/// After activating constraints
[self.view layoutIfNeeded];
  1. 您应该尝试分别使用 leadingAnchortrailingAnchor 而不是 leftAnchorrightAnchor

如果没有任何帮助,我认为您的视图控制器的视图情节提要设置未更新为使用自动布局。在那种情况下,你可以试试这个 -

_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:theConfiguration];
_webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self.view addSubview:_webView];

请注意,在这种情况下 - 您必须删除所有与约束相关的代码。

/*
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[ ...... ]];
*/

经过几天的查找,终于找到了错误的原因。 在 UIView 扩展文件中覆盖 center 属性

#import <UIKit/UIKit.h>

@interface UIView (FrameExtension)

@property CGPoint center;

@end

.

#import "UIView+FrameExtension.h"

@implementation UIView (FrameExtension)

- (CGPoint)center {
     return CGPointMake(self.frame.origin.x + self.frame.size.width / 2,
                        self.frame.origin.y + self.frame.size.height / 2);
}

- (void)setCenter:(CGPoint)center {
     CGRect frame = self.frame;
     frame.origin = CGPointMake(center.x - self.frame.size.width / 2,
                                center.y - self.frame.size.height / 2);
     self.frame = frame;
}

@end

不知何故,当加载 webview 时,它调用了 setCenter,这导致了错误。