[UIKit] Copy to Clipboard

Charlie·2022년 6월 13일
0

UIKit

목록 보기
1/2

목차

  1. 터치로 클립보드에 복사하기
  2. 복사 완료 팝업 띄우기

화면을 터치하여 Textfield의 내용을 clipboard로 복사하는 것이 생각만큼 어렵지 않았다.

터치로 클립보드에 복사하기

struct ContentView: View {
    @State private var text = ""
    @State private var buttonText = "Click to copy"
    
    private let pasteboard = UIPasteboard.general
    
    var body: some View {
        VStack {
            TextField("Placeholder", text: $text)
                .textFieldStyle(.roundedBorder)
                
            Button {
                copyToPasteboard()
            } label: {
                Text(buttonText)
            }
            
            Button {
                paste()
            } label: {
                Text("Paste")
            }
        }
    }
    
    func copyToPasteboard() {
        pasteboard.string = text
        
        buttonText = "copied"
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            buttonText = "Click to copy"
        }
    }

    func paste() {
        if let string = pasteboard.string {
            text = string
        }
    }
}

복사 완료 팝업 띄우기

위 예제와 같이 DispatchQueue를 사용하여 시간을 두고 복사가 완료되었다는 것을 알릴 수도 있지만, 모달 또는 팝업 등의 형태로 알릴 수도 있다.
여러 형태로 사용자에게 알릴 수 있겠지만 돈워리 앱을 만드는 과정에서 팝업은 아래 레퍼런스에 남긴 링크의 코드를 사용하였다.

Reference

Apple Developer Documentation - UIPasteboard
How to copy any Text to Clipboard in SwiftUI Tutorial (iOS 2022)
취준생을 위한 스위프트UI 앱만들기 강좌 토스트, 팝업 - SwiftUI fundamental Tutorial (2020) - Toast, popup

profile
Hello

0개의 댓글