1

我正在尝试在 SwiftUI 中实现 PKPaymentButton,但我无法弄清楚如何为 PKPaymentButton 创建包装器。我的代码如下:

struct ApplePayButton: UIViewRepresentable {

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

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

我收到以下错误:

  • 对“ApplePayButton”类型的无效关联类型“UIViewType”的引用
  • 类型“ApplePayButton”不符合协议“UIViewRepresentable”

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

4

2 回答 2

2

声明应如下所示:

import SwiftUI
import UIKit
import PassKit

struct ApplePayButton: UIViewRepresentable {


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

    func updateUIView(_ uiView: PKPaymentButton, 
                 context: UIViewRepresentableContext<ApplePayButton>) {
        //
    }
}
于 2019-11-21T17:00:36.273 回答
1

这让我永远想通了,所以也许有人会觉得这很有帮助:

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

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()
    }
}
于 2020-10-20T16:32:57.920 回答