如何为PKPaymentButton创建包装器

时间:2019-11-21 16:27:40

标签: swift wrapper swiftui applepay uiviewrepresentable

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

dplyr

我遇到以下错误:

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

有人能做到这一点吗,还是有人有更好的方法在SwiftUI中实现Apple Pay?

2 个答案:

答案 0 :(得分:1)

声明应类似于以下内容:

import SwiftUI
import UIKit
import PassKit

struct ApplePayButton: UIViewRepresentable {


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

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

答案 1 :(得分: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()
    }
}