SwiftUI macOS NSTextViewを使う とりあえず配置

Framework Integration

Document

Documentより(DeepL翻訳)

SwiftUIビューを既存のアプリに統合し、AppKit、UIKit、WatchKitビューとコントローラをSwiftUIビュー階層に埋め込みます。

NSViewRepresentableプロトコル実装

import AppKit
import SwiftUI

struct AppKitNSTextView: NSViewRepresentable {
    typealias NSViewType = NSTextView
    
    let width: CGFloat
    let height: CGFloat
    
    func makeNSView(context: Context) -> NSTextView {
        let view = NSTextView(frame: NSRect(x: 0, y: 0, width: width, height: height))
        return view
    }
    
    func updateNSView(_ nsView: NSTextView, context: Context) {
    }
}

SwiftUIからコール

import SwiftUI

struct ContentView: View {
    @State var memo = ""
    
    let appDelegate: AppDelegate = NSApplication.shared.delegate as! AppDelegate
    
    var body: some View {
        AppKitNSTextView(width: appDelegate.window.frame.width,
                         height: appDelegate.window.frame.height)
    }
}


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

Swift

Posted by shi-n