如何将方法处理程序传递回SwiftUI



我是Swift的新手,目前我正在实现验证码的UI,但我不知道该怎么做。我发现了一些与我在StackOverflow上的要求类似的东西,我只是复制并传递到我的项目中,然后正如你在VerificationView_Previews中看到的那样,我们需要将方法处理程序传递回来。我不知道如何传递它。请

//
//  VerificationView.swift
//  UpdateHistory
//
//  Created by Admin on 4/21/21.
//
import SwiftUI
public struct VerificationView: View {
var maxDigits: Int = 6
var label = "Enter One Time Password"
@State var pin: String = ""
@State var showPin = true
var handler: (String, (Bool) -> Void) -> Void
public var body: some View {
VStack {
Text(label).font(.title)
ZStack {
pinDots
backgroundField
}
}
}
private var pinDots: some View {
HStack {
Spacer()
ForEach(0..<maxDigits) { index in
Image(systemName: self.getImageName(at: index))
.font(.system(size: 60, weight: .thin, design: .default))
Spacer()
}
}
}
private func getImageName(at index: Int) -> String {
if index >= self.pin.count {
return "square"
}
if self.showPin {
return self.pin.digits[index].numberString + ".square"
}
return "square"
}
private var backgroundField: some View {
let boundPin = Binding<String>(get: { self.pin }, set: { newValue in
self.pin = newValue
self.submitPin()
})

return TextField("", text: boundPin, onCommit: submitPin)
.accentColor(.clear)
.foregroundColor(.clear)
.keyboardType(.numberPad)
}

private var showPinButton: some View {
Button(action: {
self.showPin.toggle()
}, label: {
self.showPin ?
Image(systemName: "eye.slash.fill").foregroundColor(.primary) :
Image(systemName: "eye.fill").foregroundColor(.primary)
})
}
private func submitPin() {
if pin.count == maxDigits {
handler(pin) { isSuccess in
if isSuccess {
print("pin matched, go to next page, no action to perfrom here")
} else {
pin = ""
print("this has to called after showing toast why is the failure")
}
}
}
}
}
extension String {
var digits: [Int] {
var result = [Int]()
for char in self {
if let number = Int(String(char)) {
result.append(number)
}
}
return result
}
}
extension Int {
var numberString: String {

guard self < 10 else { return "0" }

return String(self)
}
}
struct VerificationView_Previews: PreviewProvider {
static var previews: some View {
VerificationView() // need to pass method handler
}
}

为了查看,您可以简单地这样使用。预览不需要第二个参数

struct VerificationView_Previews: PreviewProvider {

static var previews: some View {
VerificationView { (pin, _) in
print(pin)
}
}
}

你也可以像这样使用

struct VerificationView_Previews: PreviewProvider {

var successClosure: (Bool) -> Void

static var previews: some View {
VerificationView { (pin, successClosure) in

}
}
}

最新更新