「Swift 今更!?PencilKit」のSwiftUI・iPadOS14.5版にSwipeを追加してみよう!!

Swift 今更!?PencilKit

以前の記事「Swift 今更!?PencilKit」

「Swift 今更!?PencilKit」のSwiftUI・iPadOS14.5版

以前の記事「「Swift 今更!?PencilKit」のSwiftUI・iPadOS14.5版」

「Swift 今更!?PencilKit」のSwiftUI・iPadOS14.5版にSwipeを追加してみよう!!

当然見た目は変わらない

  • UIViewControllerRepresentableを使用する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import SwiftUI
import PencilKit
 
struct ExampleControllerView: View {
    var body: some View {
        ZStack {
            Image("template")
                .resizable()
                .scaledToFit()
                .edgesIgnoringSafeArea(.all)
            PencilKitViewControllerView()
        }
    }
}
 
struct ExampleControllerView_Previews: PreviewProvider {
    static var previews: some View {
        ExampleControllerView()
    }
}
 
struct PencilKitViewControllerView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> PencilKitViewController {
        return PencilKitViewController()
    }
 
    func updateUIViewController(_ controller: PencilKitViewController, context: Context) {}
}
 
class PencilKitViewController: UIViewController {
    var pkcanvasview: PKCanvasView?
    let pktoolpicker = PKToolPicker()
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        self.pkcanvasview = PKCanvasView(frame: .zero)
        if let view = self.pkcanvasview {
            view.isOpaque = false
            view.backgroundColor = .clear
            view.overrideUserInterfaceStyle = .light
            self.pktoolpicker.addObserver(view)
            self.pktoolpicker.setVisible(true, forFirstResponder: view)
            view.becomeFirstResponder()
            self.view = view
 
            let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeLeft(sender:)))
            swipeLeft.direction = .left
            view.addGestureRecognizer(swipeLeft)
 
            let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeRight(sender:)))
            swipeRight.direction = .right
            view.addGestureRecognizer(swipeRight)
        }
    }
 
    @objc func swipeLeft(sender: UISwipeGestureRecognizer) {
        print("Swipe left.")
    }
 
    @objc func swipeRight(sender: UISwipeGestureRecognizer) {
        print("Swipe right.")
    }
}

SwiftSwift,SwiftUI

Posted by shi-n