facebook twitter hatena line email

Ios/swift/WebView

提供: 初心者エンジニアの簡易メモ
2016年11月21日 (月) 10:36時点におけるAdmin (トーク | 投稿記録)による版 (戻る進む)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

WebViewとは

ブラウザの表示ができるView

使い方

  1. StroyboardでViewControllerをstoryboard画面内にドラッグし貼り付ける
  2. ViewController内にWebViewをドラッグし貼り付ける
  3. WebViewを選択しAutolayoutを画面いっぱい(上下を0、左右を-20)で指定する
  4. 作成したViewControllerのクラス名を"WebViewController"にし
  5. WebViewControllerのStoryboardIdを"WebViewControllerId"にする
  6. WebViewControllerのクラスファイルを作成し以下のように
  7. WebViewオブジェクトとの紐付けもする

-WebViewController.swift

import UIKit
class WebViewController: UIViewController ,UIWebViewDelegate {
   @IBOutlet var mainWebView : UIWebView!
   private var _targetURL = "http://google.com"
   override func viewDidLoad() {
       super.viewDidLoad()
       mainWebView.delegate = self;
       loadAddressURL()
   }
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
   func loadAddressURL() {
       let requestURL = NSURL(string: _targetURL)
       let req = NSURLRequest(URL: requestURL!)
       mainWebView.loadRequest(req)
   }
}

以下エラーが出る場合

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController

storyboardのWebViewControllerのCustomClassのモジュール名がNoneになってる場合は一旦xcodeを再起動する(current-project名などになってればok)

htmlを直で記述する場合は以下のように

mainWebView.loadHTMLString("hogehoge", baseURL: requestURL)

長文半角文字列でブラウザの枠を突き抜ける場合

普通にcssの以下のようなstyleを追加

webviewのリンクからからネイティブControllerへページ遷移

webViewメソッドが用意されている

   html = "<a href='native://hogehoge'>hogehoge</a>"
   func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       if let url = request.URL?.absoluteString {
           if url.hasPrefix("native://") {
               print(url)
               return false  // ページ遷移を行わないようにfalseを返す
           }
       }
       return true
   }

参考:http://qiita.com/tyfkda/items/14cebb890f1d3fa40bda

上下スクロール

class WebViewController: UIViewController ,UIWebViewDelegate, UIScrollViewDelegate {
   override func viewDidLoad() {
       super.viewDidLoad()
       mainWebView.delegate = self;
       mainWebView.scrollView.delegate = self
   }
   var scrollBeginingPoint: CGPoint! = CGPoint(x: 0, y: 0)
   func scrollViewWillBeginDragging(scrollView: UIScrollView) {
       scrollBeginingPoint = scrollView.contentOffset;
   }
   func scrollViewDidScroll(scrollView: UIScrollView) {
       if scrollBeginingPoint.y < scrollView.contentOffset.y {
           print("下へスクロール")
       }else{
           print("上へスクロール")
       }
   }
}

戻る進む

if (self.webView.canGoBack) {
    self.webView.goBack()
}
if (self.webView.canGoForward) {
    self.webView.goForward()
}