WKWebView in Interface Builder

前端 未结 12 871
南旧
南旧 2020-11-30 01:51

It seems that the IB object templates in XCode 6 beta are still creating old-style objects (UIWebView for iOS and WebView for OSX). Hopefully Apple will update them for the

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 02:44

    With Xcode 8 this is now possible, but the means of achieving it is a little hacky to say the least. But hey, a working solution is a working solution, right? Let me explain.

    WKWebView's initWithCoder: is no longer annotated as "NS_UNAVAILABLE". It now looks as shown below.

    - (nullable instancetype)initWithCoder:(NSCoder *)coder NS_DESIGNATED_INITIALIZER;
    

    Start by subclassing WKWebView and override initWithCoder. Instead of calling super initWithCoder, you'll need to use a different init method, such as initWithFrame:configuration:. Quick example below.

    - (instancetype)initWithCoder:(NSCoder *)coder
    {
        // An initial frame for initialization must be set, but it will be overridden 
        // below by the autolayout constraints set in interface builder. 
        CGRect frame = [[UIScreen mainScreen] bounds];
        WKWebViewConfiguration *myConfiguration = [WKWebViewConfiguration new];
    
        // Set any configuration parameters here, e.g.
        // myConfiguration.dataDetectorTypes = WKDataDetectorTypeAll; 
    
        self = [super initWithFrame:frame configuration:myConfiguration];
    
        // Apply constraints from interface builder.
        self.translatesAutoresizingMaskIntoConstraints = NO;
    
        return self;
    }
    

    Over in your Storyboard, use a UIView and give it a custom class of your new subclass. The rest is business as usual (setting auto-layout constraints, linking the view to an outlet in a controller, etc).

    Finally, WKWebView scales content differently to UIWebView. Many people are likely going to want to follow the simple advice in Suppress WKWebView from scaling content to render at same magnification as UIWebView does to make WKWebView more closely follow the UIWebView behaviour in this regard.

提交回复
热议问题