The Util Designer
在 SwiftUI 中實現copy和Paste資料
xcode 13.4.1, swift 5.5, iOS 15.4
2022-10-08
copy和paste是大家最常見的也是天天在使用的功能,這次來講講如何簡單的為自己的App實現這兩個小功能,以便與其他App進行簡單的資料交互。
1. 為了演示這兩個功能,我們只需要一個TextEdit和兩個Button(一個作copy用一個作paste用),佈局如下:
import SwiftUI

struct CopyAndPaste: View {
    @State private var text : String = ""
    
    var body: some View {
        VStack {
            TextField("Insert text here", text: $text)
            HStack {
                Spacer()
                Button {
                } label: {
                    Label("Copy", systemImage: "doc.on.doc.fill")
                }
                Spacer()
                Button {
                } label: {
                    Label("Paste", systemImage: "doc.on.clipboard")
                }
                Spacer()
            }
        }
    }
}
2. 先使用UIPasteboard元件來實現Paste功能:

import SwiftUI

struct CopyAndPaste: View {
    @State private var text : String = ""
    
    var body: some View {
        VStack {
            TextField("Insert text here", text: $text)
            HStack {
                Spacer()
                Button {
                } label: {
                    Label("Copy", systemImage: "doc.on.doc.fill")
                }
                Spacer()
                Button {
                    paste()
                } label: {
                    Label("Paste", systemImage: "doc.on.clipboard")
                }
                Spacer()
            }
        }
    }
    
    func paste() {
        if let string = UIPasteboard.general.string {
            text = string
        }
    }
}
2. 再使用UIPasteboard元件來實現Copy功能:
import SwiftUI

struct CopyAndPaste: View {
    @State private var text : String = ""
    
    var body: some View {
        VStack {
            TextField("Insert text here", text: $text)
            HStack {
                Spacer()
                Button {
                    copy()
                } label: {
                    Label("Copy", systemImage: "doc.on.doc.fill")
                }
                Spacer()
                Button {
                    paste()
                } label: {
                    Label("Paste", systemImage: "doc.on.clipboard")
                }
                Spacer()
            }
        }
    }
    
    func paste() {
        if let string = UIPasteboard.general.string {
            text = string
        }
    }
    
    func copy() {
        UIPasteboard.general.string = self.text
    }
}