一个 SwiftUI 的 LabeledContentStyle
,当其标签被点击时,将焦点移动到 LabeledContent
的内容上。
这个软件包的灵感来自于 HTML 中 <label>
的工作方式。当 <label>
与表单控件关联时,点击标签会将焦点移动到关联的表单控件。在 iOS 的“设置”应用中,表单中带标签的文本字段也可见到相同的行为。SwiftUI 提供了 LabeledContent
来将标签与内容关联,但是当你点击标签时,它没有相同的焦点功能。这个软件包解决了这个问题。
可以使用 Swift 包管理器安装 LabeledContentInteractiveFocus
File
> Add Package Dependencies
https://github.com/yakimvanzuijlen/LabeledContentInteractiveFocus.git
Add Package
或者将其添加到你的 Package.swift
文件中
dependencies: [
.package(url: "[https://github.com/yakimvanzuijlen/LabeledContentInteractiveFocus.git]", from: "1.0.0")
]
首先,导入库。
import LabeledContentInteractiveFocus
你可以使用 labeledContentInteractiveFocus()
视图修饰符或作为 LabeledContentStyle
来应用交互。它们具有相同的效果。
struct ContentView: View {
@State private var name = ""
@State private var password = ""
var body: some View {
Form {
LabeledContent("Name") {
TextField("", text: $name)
.textContentType(.name)
}
LabeledContent("Password") {
SecureField("", text: $password)
.textContentType(.newPassword)
}
}
.labeledContentInteractiveFocus()
}
}
在 macOS 上,你也可以将其与标准文本字段标签一起使用。由于在 macOS 上文本字段标签已经可见,因此无需将文本字段包装在 LabeledContent
中。
struct Example: View {
@State private var animal = ""
var body: some View {
Form {
#if os(macOS)
// On macOS the label is always visible, so LabeledContent is not necessary.
TextField("Animal", text: $animal)
#else
// Wrap in a labeled content to provide a label that is always visible.
LabeledContent("Animal") {
TextField("", text: $animal)
}
#endif
}
#if os(macOS)
.formStyle(.grouped)
#endif
.labeledContentInteractiveFocus()
}
}
你可以使用 interactiveFocus
作为 InteractiveFocusLabeledContentStyle()
的简写。
struct ContentView: View {
@State private var productMaterial = ""
var body: some View {
LabeledContent {
TextField("", text: $productMaterial)
} label: {
Text("Product Material").bold()
}
.labeledContentStyle(.interactiveFocus)
}
}