A preface.

This is a pitfall problem. I developed macOS project at the beginning, and the solutions I searched on the Internet basically used UIPasteboard method, but it did not work.

Later, when I developed ios projects, MACOS did not work, and I found that UIPasteboard was feasible. Therefore, it should be clear that the replication methods of ios and MacOS are different……

2. MacOS

1. The implementation

func copyToClipBoard(textToCopy: String) {
  let pasteBoard = NSPasteboard.general
  pasteBoard.clearContents()
  pasteBoard.setString(textToCopy, forType: .string)
}
Copy the code

2. Call

copyToClipBoard(textToCopy: "Hello,World!")
Copy the code

3. The IOS

1. The implementation

UIPasteboard.general.setValue(<Your-String>, forPasteboardType: kUTTypePlainText as String)
Copy the code

2. Call

UIPasteboard.general.setValue("Hello,World!", forPasteboardType: kUTTypePlainText as String)
Copy the code

4. Blog links

SwiftUI project copies strings to clipboard