質問編集履歴

1

補足にPC環境、現在のコードを全て記載しました。

2024/04/26 10:01

投稿

Gameno
Gameno

スコア10

test CHANGED
File without changes
test CHANGED
@@ -94,4 +94,90 @@
94
94
  pdfViewのoverlayProviderにtoolを上書きしても、変更されませんでした。
95
95
 
96
96
  ### 補足
97
+ yametaiさんからいただいたコードの追記
98
+ ```swift
99
+ import SwiftUI
100
+ import PencilKit
101
+ import PDFKit
102
+
103
+ struct SwiftUIView: View {
104
+ @State private var isPen = true
105
+ var body: some View {
106
+ VStack {
107
+ HStack{
108
+ Button(action: {
109
+ isPen = true
110
+ }, label: {
111
+ Text("ペン")
112
+ })
113
+ Button(action: {
114
+ isPen = false
115
+ }, label: {
116
+ Text("消しゴム")
117
+ })
118
+
119
+ }
120
+ PdfView(isPen: $isPen)
121
+ }
122
+ }
123
+ }
124
+
125
+ struct PdfView : UIViewRepresentable {
126
+ typealias UIViewType = PDFView
127
+ @Binding var isPen: Bool
128
+ let overlayProvider = OverlayCoordinator()
129
+ func makeUIView(context: Context) -> PDFView {
130
+ let pdfView: PDFView = PDFView()
131
+ if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
132
+ pdfView.pageOverlayViewProvider = overlayProvider
133
+ pdfView.document = PDFDocument(url: url)
134
+ pdfView.autoScales = true
135
+ pdfView.isInMarkupMode = true
136
+ }
137
+ return pdfView
138
+ }
139
+ func updateUIView(_ uiView: PDFView, context: Context) {
140
+
141
+ if isPen {
142
+ print("pen")
143
+ overlayProvider.setPen()
144
+ } else {
145
+ print("eraser")
146
+ overlayProvider.setEraser()
147
+ }
148
+
149
+ }
150
+ }
151
+
152
+ class OverlayCoordinator : NSObject,PDFPageOverlayViewProvider {
153
+ var pageToViewMapping = [PDFPage: PKCanvasView]() //補足追加
154
+ var canvasView: PKCanvasView = PKCanvasView()
155
+
156
+ func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {
157
+ // let canvasView = PKCanvasView()
158
+ var resultView:PKCanvasView? = nil
159
+ // 編集・追加↓
160
+ if let overlayView = pageToViewMapping[page] {
161
+ resultView = overlayView
162
+ } else {
163
+ let canvasView = PKCanvasView()
164
+ canvasView.drawingPolicy = .anyInput
165
+ canvasView.tool = PKInkingTool(.pen, width: 20)
166
+ canvasView.backgroundColor = .clear
167
+ pageToViewMapping[page] = canvasView
168
+ resultView = canvasView
169
+ }
170
+ return resultView
171
+ // 編集・追加↑
172
+ }
173
+ func setPen() {
174
+ canvasView.tool = PKInkingTool(.pen, width: 1)
175
+ }
176
+ func setEraser() {
177
+ canvasView.tool = PKEraserTool(.bitmap)
178
+ }
179
+
180
+ }
97
- 特になし
181
+ ```
182
+ 環境 macOS Ventura 13.6.6
183
+ xcode Version 15.2