You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SwiftUI中自定义iOS 16 PasteButton的外观?

解决方案

要让PasteButton和你自定义的按钮样式完全一致,你需要利用iOS 16为PasteButton提供的自定义Label能力——直接传入你想要的视图作为按钮内容,而不是依赖系统默认样式。这样既保留了PasteButton的隐私优势(无需重复弹出剪贴板权限提示),又能完全匹配你原有的按钮设计。

修改后的完整代码

import SwiftUI
import UniformTypeIdentifiers

struct ButtonView: View {
    
    private let supportedTypes: [UTType] = [UTType.public.image]
    
    var body: some View {
        VStack {
            // 自定义样式的PasteButton
            PasteButton(supportedContentTypes: supportedTypes) { itemProviders in
                // 处理粘贴逻辑
                guard let itemProvider = itemProviders.first else { return }
                if itemProvider.hasItemConformingToTypeIdentifier(UTType.public.image.identifier) {
                    itemProvider.loadObject(ofClass: UIImage.self) { image, error in
                        DispatchQueue.main.async {
                            if let uiImage = image as? UIImage {
                                // 拿到图片后的处理逻辑
                            }
                        }
                    }
                }
            } label: {
                // 直接复用原粘贴按钮的布局
                HStack {
                    Image(systemName: "doc.on.clipboard")
                    Text("Paste Photo")
                }
                .font(.title)
            }
            .padding(.bottom, 8)

            // 原相册选择按钮
            Button {
                // 打开相册逻辑
            } label: {
                Image(systemName: "photo.on.rectangle.angled")
                Text("Pick a Photo")
            }
            .font(.title)
        }
    }
}

关键说明

  • 直接给PasteButton传递label参数,传入自定义的HStack视图,就能完全控制按钮的图标、文本、字体等样式,和相册按钮保持视觉统一。
  • 之前直接添加.font(.title)无效的原因是:该修饰符作用在PasteButton容器上,而非内部的默认文本组件,自定义Label后可直接在视图上设置字体。
  • 这种方式完全符合WWDC 2022提到的自定义适配要求,既遵守系统隐私规则,又能完美融入应用界面。

内容的提问来源于stack exchange,提问作者gohnjanotis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:05:23