2

I have a custom struct which is represented with a view. When you click on this view the view gets selected. Now I want the struct to be copied to the clipboard by pressing "cmd + c" or by going to "Edit > Copy" at the Mac menubar if the item is selected. How can I achieve that?

import SwiftUI

struct ContentView: View {
    
    @State var item: Item = Item() // item to copy on clipboard 
    @State var isSelected: Bool = false // make item copyable if true
    
    var body: some View {
        ZStack {
            
            Color.clear
                .contentShape(Rectangle())
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .edgesIgnoringSafeArea(.all)
                .onTapGesture {
                    isSelected = false
                }
            
            ItemRepresentation(item: item)
                .onTapGesture {
                    isSelected = true
                }
            
            if isSelected {
                SelectionIndicator(item: item)
            }
            
        }
        .onAppear(perform: {
            item.width = Double.random(in: 20...500)
            item.height = Double.random(in: 20...500)
            item.cornerRadius = Double.random(in: 1...100)
        })
        
    }
    
    @ViewBuilder func ItemRepresentation(item: Item) -> some View {
        Text(item.title)
            .frame(width: item.width, height: item.height)
            .background(Color.red)
            .frame(width: item.width, height: item.height)
            .cornerRadius(item.cornerRadius, antialiased: true)
    }  
    
    @ViewBuilder func SelectionIndicator(item: Item) -> some View {
        Rectangle()
            .stroke(Color.blue, lineWidth: 2)
            .frame(width: item.width + 20, height: item.height + 20)
    }  
    
}

struct Item: Codable { // custom struct to copy
    
    var title: String = "Text"
    var width: Double = 0
    var height: Double = 0
    var cornerRadius: Double = 0
    
}

0 Answers0