CopyButton.swift (1342B)
1 import SwiftUI 2 3 public struct CopyButton: View { 4 private let value: String 5 private let onCopied: (() -> Void)? 6 @State private var copied = false 7 8 public init(value: String, onCopied: (() -> Void)? = nil) { 9 self.value = value 10 self.onCopied = onCopied 11 } 12 13 public var body: some View { 14 Button { 15 Task { @MainActor in 16 UIPasteboard.general.string = value 17 } 18 let gen = UINotificationFeedbackGenerator() 19 gen.notificationOccurred(.success) 20 withAnimation(.easeInOut(duration: 0.12)) { copied = true } 21 onCopied?() 22 DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { 23 withAnimation(.easeInOut(duration: 0.12)) { copied = false } 24 } 25 } label: { 26 ZStack { 27 Image(systemName: "doc.on.doc") 28 .opacity(copied ? 0 : 1) 29 Image(systemName: "checkmark.circle.fill") 30 .opacity(copied ? 1 : 0) 31 } 32 .frame(width: 24, height: 24) 33 .font(.system(size: 17, weight: .semibold)) 34 } 35 .buttonStyle(.plain) 36 .foregroundStyle(copied ? .green : .accentColor) 37 .contentTransition(.opacity) 38 .accessibilityLabel(copied ? "Copied" : "Copy") 39 } 40 }