回答編集履歴

1

戻るボタンをツールバーなどで用意した際ならのコード

2020/04/28 08:10

投稿

TakuyaAso
TakuyaAso

スコア1361

test CHANGED
@@ -13,3 +13,129 @@
13
13
  }
14
14
 
15
15
  ```
16
+
17
+
18
+
19
+
20
+
21
+ スワイプでも戻れます。
22
+
23
+ ```swift
24
+
25
+ self.webView.allowsBackForwardNavigationGestures = true
26
+
27
+ ```
28
+
29
+
30
+
31
+ 一般的にはツールバーに < とか > のボタンを用意して
32
+
33
+ 下記のメソッドを各ボタンのアクションに充てる感じかなと。
34
+
35
+
36
+
37
+ ```swift
38
+
39
+ // 戻るとき
40
+
41
+ if (self.webView.canGoBack) {
42
+
43
+ self.webView.goBack()
44
+
45
+ }
46
+
47
+
48
+
49
+ // 進むとき
50
+
51
+ if (self.webView.canGoForward) {
52
+
53
+ self.webView.goForward()
54
+
55
+ }
56
+
57
+ ```
58
+
59
+
60
+
61
+ 戻れる,進めるようになった際にボタンを有効/無効にしたい場合は
62
+
63
+ KVOで監視する形になります。例えばこんな感じかなと。
64
+
65
+
66
+
67
+ ```swift
68
+
69
+ // 宣言
70
+
71
+ var observations = [NSKeyValueObservation]() // KVOに使う(classの中)
72
+
73
+ ```
74
+
75
+
76
+
77
+ viewDidloadとかに
78
+
79
+
80
+
81
+ ```swift
82
+
83
+ observations.append(webView.observe(.canGoBack, options: .new){ _, change in
84
+
85
+ if let value = change.newValue {
86
+
87
+ DispatchQueue.main.async {
88
+
89
+ self.backButton.isEnabled = value
90
+
91
+ self.backButton.alpha = value ? 1.0 : 0.4
92
+
93
+ }
94
+
95
+ }
96
+
97
+ })
98
+
99
+
100
+
101
+ observations.append(webView.observe(.canGoForward, options: .new){ _, change in
102
+
103
+ if let value = change.newValue {
104
+
105
+ DispatchQueue.main.async {
106
+
107
+ self.forwardButton.isEnabled = value
108
+
109
+ self.forwardButton.alpha = value ? 1.0 : 0.4
110
+
111
+ }
112
+
113
+ }
114
+
115
+ })
116
+
117
+ ```
118
+
119
+
120
+
121
+ 最後にボタンのアクション。
122
+
123
+
124
+
125
+ ```swift
126
+
127
+ @IBAction func goBackTapped(_ sender: UIButton) {
128
+
129
+ webView.goBack()
130
+
131
+ }
132
+
133
+
134
+
135
+ @IBAction func goForwardTapped(_ sender: UIButton) {
136
+
137
+ webView.goForward()
138
+
139
+ }
140
+
141
+ ```