SwiftUI macOS NSTextViewを使う 値変更をSwiftUIに連携

SwiftUI macOS NSTextViewを使う とりあえず配置」の続きになります。

GitHub:uRaKaMi

Coordinator関連実装

import AppKit
import SwiftUI

struct AppKitNSTextView: NSViewRepresentable {
    typealias NSViewType = NSTextView
    
    @Binding var string: String

    let width: CGFloat
    let height: CGFloat
    
    func makeNSView(context: Context) -> NSTextView {
        let view = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: height))
        view.delegate = context.coordinator
        return view
    }
    
    func updateNSView(_ nsView: NSTextView, context: Context) {
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(appKitNSTextView: self)
    }
}

extension AppKitNSTextView {
    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: AppKitNSTextView
        
        init(appKitNSTextView: AppKitNSTextView) {
            self.parent = appKitNSTextView
        }
        
        func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
            return true
        }
        
        
        func textDidChange(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }
            self.parent.string = textView.string
        }
    }
}

SwiftUI側

import SwiftUI

struct ContentView: View {
    @State var urakami = ""
    
    let appDelegate: AppDelegate = NSApplication.shared.delegate as! AppDelegate
    
    var body: some View {
        VStack {
            AppKitNSTextView(string: $urakami,
                             width: appDelegate.window.frame.width,
                             height: appDelegate.window.frame.height - 100)
            Text(urakami)
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Swift

Posted by shi-n