SwiftUI - Clipboard



A clipboard is a small temporary storage area where we can store data such as text, images, files, etc., immediately after copying or cutting, and we can paste this data anywhere in the app. It is a temporary area, so it holds only one item or content at a time, so whenever we copy or cut something new, it will replace it with the old one.

It will remove all the data whenever the system is shut down or restarted. It also allows us to share data from one app to another, which means we can copy or cut data from one app and paste it into another. It can also store complex data objects or custom data types.

Clipboard perform two main operations and they are −

  • Copying data

  • Pasting data

Copying data to the clipboard in SwiftUI

In SwiftUI, no direct method or modifier is available for copying data in the clipboard. So, we have to use the UIPasteboard class of UIKit to copy data to the clipboard. This class allows us to interact with the system clipboard or pasteboard to easily copy and paste data into it. It is available only for iOS and iPad. Using this class, we can copy and paste various types of data such as text, images, URLs, etc.

Syntax

Following is the syntax −

// Copying text
UIPasteboard.general.string = "Hello, world!"

// Copying URL
UIPasteboard.general.url = URL(string: "https://www.abc.com")

// Copying image
UIPasteboard.general.image = UIImage(named: "myImage")

// Copying multiple data
UIPasteboard.general.items = [
    [UIPasteboard.typeAutomatic: "TutorialsPoint"],
    [UIPasteboard.typeAutomatic: UIImage(named: "myImage")!]
]

Example

The following SwiftUI program is used to copy data in the clipboard.

import SwiftUI
import UIKit

struct ContentView: View {
   @State private var myText = "Welcome To TutorialsPoint"

   var body: some View {
      VStack{
         Text(myText)
            .font(.title)
            .padding()

         Button(action: {
            
            // Copying text to clipboard
            UIPasteboard.general.string = myText
         }) {
            Text("Copy to Clipboard")
               .padding()
               .background(.pink.opacity(0.8))
               .foregroundStyle(.white)
               .cornerRadius(10)
         }
      }
   }
}
#Preview {
   ContentView()
}

Pasting data from the clipboard in SwiftUI

We use the UIPasteboard class of UIKit to read data from the clipboard and display it on the given view. It can read any type of data, such as texts, images, URLs, etc. We can also check if the clipboard contains the specified contain or not with the help of hasString, hasURLs, hasImages, and hasColor properties.

Syntax

Following is the syntax −

if let text = UIPasteboard.general.string {
   // Handle text
} else if let image = UIPasteboard.general.image {
   // Handle image
}else if let URLs = UIPasteboard.general.url{
   // Handle urls
}

Example

The following SwiftUI program is used to paste data from the clipboard.

import SwiftUI
import UIKit

struct ContentView: View {
   @State private var myText = "Welcome To TutorialsPoint"
   @State private var isCopy = false
   @State private var isPaste = false
   
   var body: some View {
      VStack{
         Text(myText).font(.title).padding()
         Button(action: {            
            // Copying text to clipboard
            UIPasteboard.general.string = myText
            isCopy = true

            // Reset the message after a delay
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
               isCopy = false
            }
         }) {
            Text("Copy Text to Clipboard")
               .padding()
               .background(Color.pink.opacity(0.8))
               .foregroundColor(.white)
               .cornerRadius(10)
         }

         if isCopy {
            Text("Copied successfully!")
               .bold()
               .font(.headline)
               .transition(.opacity)
               .animation(.easeInOut(duration: 0.3), value: isCopy)
         }
         Button(action: {            
            // Pasting text from the clipboard
            if let clippedText = UIPasteboard.general.string {
               myText = clippedText
               isPaste = true
               
               // Reset the message after a delay
               DispatchQueue.main.asyncAfter(deadline: .now() + 2) {isPaste = false}
            } else {
               myText = "No text found"
            }
         }) {
            Text("Paste Text from Clipboard")
               .padding()
               .background(Color.purple.opacity(0.8))
               .foregroundColor(.white)
               .cornerRadius(10)
         }
         if isPaste {
            Text("Pasted successfully!")
               .bold()
               .font(.headline)
               .transition(.opacity)
               .animation(.easeInOut(duration: 0.3), value: isPaste)
         }         
      }.padding()
   }
}

#Preview {
   ContentView()
}
Advertisements