如何为 PKPaymentButton 创建包装器

How to create a wrapper for PKPaymentButton

我正在尝试在 SwiftUI 中实现 PKPaymentButton,但我不知道如何为 PKPaymentButton 创建包装器。我的代码如下:

struct ApplePayButton: UIViewRepresentable {

    func makeUIViewController(context: Context) -> PKPaymentButton {
        return PKPaymentButton.init()
    }

    func updateUIView(_ uiView: ApplePayButton.UIViewType, context: UIViewRepresentableContext<ApplePayButton>) {
        //
    }
}

我收到以下错误:

有没有人能够做到这一点,或者有没有人有更好的方法在 SwiftUI 中实现 Apple Pay?

声明应如下所示:

import SwiftUI
import UIKit
import PassKit

struct ApplePayButton: UIViewRepresentable {


    func makeUIView(context: Context) -> PKPaymentButton {
        return PKPaymentButton()
    }

    func updateUIView(_ uiView: PKPaymentButton, 
                 context: UIViewRepresentableContext<ApplePayButton>) {
        //
    }
}

我花了很长的时间才弄明白,所以也许有人会觉得这有帮助:

基本上,仅将按钮包装在 UIViewRepresentable 中是不够的。你必须把它放在一个 ButtonStyle 中,然后用它来设计一个 SwiftUI 按钮。如果不这样做,您的付款 sheet 似乎会中断!我不确定为什么这是真的,但这是它应该工作的代码:

import SwiftUI
import UIKit
import PassKit

struct PaymentButton: View {
    var body: some View {
        Button(action: { /* Custom payment code here */ }, label: { EmptyView() } )
            .buttonStyle(PaymentButtonStyle())
    }
}

struct PaymentButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        return PaymentButtonHelper()
    }
}  
    
struct PaymentButtonHelper: View {
    var body: some View {
        PaymentButtonRepresentable()
            .frame(minWidth: 100, maxWidth: 400)
            .frame(height: 60)
            .frame(maxWidth: .infinity)
    }
}

extension PaymentButtonHelper {
    struct PaymentButtonRepresentable: UIViewRepresentable {
    
    var button: PKPaymentButton {
        let button = PKPaymentButton(paymentButtonType: .buy, paymentButtonStyle: .black) /*customize here*/
        button.cornerRadius = 4.0 /* also customize here */
        return button
    }
     
    func makeUIView(context: Context) -> PKPaymentButton {
        return button
    }
    func updateUIView(_ uiView: PKPaymentButton, context: Context) { }
}

用法将是:

struct ContentView: View {
    var body: some View {
        PaymentButton()
    }
}