0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WebViewの表示方法

Posted at

#WebViewをサクッと表示!!

まず、ViewController.fileにWebKitをimportします。

ViewController.swift
import UIKit
import WebKit
 
class ViewController: UIViewController {
    @IBOutlet weak var webView: WKWebView!

    override func viewDidAppear(_ animated: Bool){
        }
    } 

次に、main.storyboardへ。
WebKit Viewを右上の「+」 ボタンから選択し、ViewControllerへ貼り付け。

スクリーンショット 2020-08-01 21.04.34.png

次にwebViewを表示させるコードを書きます。

ViewController.swift
import UIKit
import WebKit
 
class ViewController: UIViewController {
    @IBOutlet weak var webView: WKWebView!
    var topPadding:CGFloat = 0

    override func viewDidAppear(_ animated: Bool){
        print("viewDidAppear")
        
        if #available(iOS 11.0, *) {
            // 'keyWindow' was deprecated in iOS 13.0: Should not be used for applications
            let window = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
            topPadding = window!.safeAreaInsets.top
        }

        let webUrl = URL(string: "https://www.google.com/")!
        let myRequest = URLRequest(url: webUrl)
        webView.load(myRequest)
 
        // インスタンスをビューに追加
        self.view.addSubview(webView)
}

これでオッケーです!
ただ、これでシュミレーターを立ち上げると・・・

スクリーンショット 2020-08-01 21.20.41.png この様に、エラーが出てしまいます。 どうやら原因はフレームワークが追加されていないからとのこと。 ということで、追加。 スクリーンショット 2020-08-01 21.03.11.png

これで完成です!
webViewを表示するのは非常に簡単ですね!
ビューアーなどの記事サイトを表示させる時に活躍しそうですね。
webkitViewの使用方法でした!ありがとうございました。
            スクリーンショット 2020-08-01 21.25.19.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?