Search code examples
iosobjective-cxcodewkwebview

WKWebView show content wrong frame in old project


I have an old iOS project using Objective C. When I add a WKWebView to a 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]];

If I install app via Xcode with iOS 14, webview works fine, but after I disconnect Xcode and open app directly, webview show content with wrong frame. If I build app in iOS 12.5 via Xcode, web view also show content with wrong frame. If I create new project from Xcode 12.5, and using same code, it works fine.

This is screenshot when open app via Xcode build

https://i.sstatic.net/rYb3M.png

And this is screenshot when open app directly:

https://i.sstatic.net/4q0uD.png


Solution

  • After spending a few days searching, I finally found the cause of the error. In a UIView Extension file overridden center property

    #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
    

    Somehow, when loading the webview, it called setCenter which caused the error.