一个用于简化表单及其字段管理的 Swift 包。专注于 SwiftUI。
String
类型的验证和字段,例如开关、滑块、选择、多选等等。@FocusState
API 配合良好。您可以像这样定义一个表单状态,使用一个简单的结构体,而不是为每个字段定义多个状态属性。
struct SignupForm {
var name: String
var email: String
var password: String
var acceptedPrivacyPolicy: Bool
}
要为字段设置预填充值,您可以使用默认属性值(或者如果您喜欢,可以使用一些静态实例)。
struct SignupForm {
var name = String()
var email = String()
var password = String()
var acceptedPrivacyPolicy = false
}
要声明表单的验证逻辑,您可以创建一个验证数组。
let validations: [FormValidation<SignupForm>] = [
FormValidation(for: \.name, description: "Name must be filled in.", rule: .required),
FormValidation(for: \.email, description: "Email must be filled in.", rule: .required),
FormValidation(for: \.email, description: "Email is not in in valid format.", rule: .email),
FormValidation(for: \.password, description: "Password is required.", rule: .required),
FormValidation(for: \.password, description: "Password must be longer than 6 characters") { $0.count > 6 },
FormValidation(for: \.acceptedPrivacyPolicy, description: "You need to accept privacy policy.", rule: .hasToBeOn)
]
如果您想使用该包进行焦点管理,您可以定义一个键路径数组作为字段顺序。
let fieldOrder: [PartialKeyPath<Self>] = [\.name, \.email, \.password]
声明表单后,您可以在视图中使用它。
struct SignupView: View {
@State private var state = FormState(form: SignupForm())
@FocusState private var focus: PartialKeyPath<SignupForm>?
var body: some View {
Form {
Section {
TextField("Name", text: $state.form.name)
.focused($focus, equals: \.name)
.onSubmit {
state.submit(field: \.name, updating: &focus)
}
ForEach(errors, id: \.self, content: Text.init)
.font(.footnote)
.foregroundColor(.red)
}
...
Section {
Button(action: submit) {
Label("Submit", systemImage: "arrow.right")
}
}
}
}
private func submit() {
if state.validate() {
...
} else {
...
}
}
}
使用 Swift Package Manager 时,使用 Xcode 11+ 进行安装,或将以下行添加到您的依赖项中。
.package(url: "https://github.com/futuredapp/FormStateKit.git", from: "0.1.0")
欢迎任何贡献。
当前的维护者和主要贡献者是 Matěj Kašpar Jirásek, matej.jirasek@futured.app。
FormStateKit 基于 MIT 许可证发布。有关更多信息,请参阅 LICENSE 文件。