LoginSignup
0
1

【Swift】WKWebViewをコードだけで使い回す

Last updated at Posted at 2021-03-01

SwiftでUITableViewのセルごとに異なるウェブサイトに遷移させたい時に便利な使い回しコード。

まずは使い回すclassを指定


import UIKit
import WebKit

class WebView : UIViewController, WKUIDelegate{
    
    var webView : WKWebView!
    var request_url : URL?
    
    override func loadView(){
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = self.request_url
        let request = URLRequest(url: url!)
        webView.load(request)
    }
}

後はtableviewのcellごとにURLを指定するだけ。

if indexPath.section == 1 {
            if indexPath.row == 0 {
                //チュートリアル
                let vc = WebView()
                vc.title = "チュートリアル"
                vc.request_url = URL(string: "https://sampe.com/tutorial/")
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
            if indexPath.row == 1 {
                //アプリの使い方
                let vc = WebView()
                vc.title = "アプリの使い方"
                vc.request_url = URL(string: "https://sampe.com//use/")
                self.navigationController?.pushViewController(vc, animated: true)
                
            }
            if indexPath.row == 2 {
                //よくある質問
                let vc = WebView()
                vc.title = "よくある質問"
                vc.request_url = URL(string: "https://sampe.com/question/")
                self.navigationController?.pushViewController(vc, animated: true)
            }
以下略

おすすめ情報

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