LoginSignup
3

More than 3 years have passed since last update.

【Swift】 WKWebViewで表示したtitleを対応するタブボタンに表示させる。

Posted at

こちらの記事で書いている、オリジナルタブブラウザアプリの、追加機能です。
タブブラウザでは、タブボタンにそのタブで開いているWebページのtitleが表示されるのが一般的だと思いますが、自作アプリでそれを実現する方法を確認しました。

開発環境

端末:MacBook Pro/MacOS 10.14.5(Mojave)
Xcode:10.2.1
Swift:5

やったこと(ポイント)

①WKWebViewで開いたWebページのtitle(titleタグの情報)を、タブボタンに表示する。

実装

画面イメージ

開いているWebページに対応するtitleがタブボタンに表示されています。
アプリ自体のUIデザインがどうかしちゃってるのは見逃して下さい。。

google
Simulator Screen Shot - iPad Air 2 - 2019-10-12 at 16.24.50.png
yahoo!japan
Simulator Screen Shot - iPad Air 2 - 2019-10-12 at 16.24.53.png
bing
Simulator Screen Shot - iPad Air 2 - 2019-10-12 at 16.24.58.png
ソースコード

要点だけ。

webView(_:didFinish:)を追加し、ページ読み込み完了時の処理を記述します。

ViewController.swift

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let targetTag = webView.tag - 10000
        let targetBtn = view.viewWithTag(targetTag) as! UIButton
        let title = webView.title
        targetBtn.setTitle(title, for: .normal)
    }

自分がどれくらい独特な書き方しちゃってるか自覚がないですが、Webページ(WKWebView)とタブボタン(UIButton)の紐付けを、tagの値を使って制御しているので上記コードのような書き方になっています。

以上です。

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
3