みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

画面いっぱいのWKWebViewを設置しただけのアプリをつくる

ウェブフロントを生業としていて、大体のことをSafariにウェブページを表示させることで解決してきた私ですが、ときどきどうしてもiPhoneアプリをつくる必要が出てくるときがあります。プッシュ通知をつかいたいときとか、ランドスケープで固定したい時とかですね。

そんなときは、ネイティブでアプリをつくって、中身をUIWebViewにし、ウェブページを表示するだけのアプリをつくってきたのですが、本日WKWebViewの存在を教えて頂いたので、乗り換えました。

Xcode8.1、Swift version 3.0.1 で実装しています。

ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController {
    private var webView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.view.addSubview(self.webView)
        self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: webView, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0.0))
        self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: webView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0))
        self.view.addConstraint(NSLayoutConstraint(item: self.topLayoutGuide, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: webView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0))
        self.view.addConstraint(NSLayoutConstraint(item: self.bottomLayoutGuide, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: webView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0.0))

        self.webView.translatesAutoresizingMaskIntoConstraints = false
        self.webView.scrollView.bounces = false
        
        let url = NSURL(string:"https://google.co.jp")
        let req = NSURLRequest(url:url as! URL)
        self.webView.load(req as URLRequest)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

スクロールしないアプリケーションを実装する予定なのでスクロールのバウンスも止めています。
あとは、ウェブページをつくって、URLをそのページに向ければ立派なアプリのできあがりです。