swift - 使用 .focused() 点击不同视图时如何移除 TextField 焦点?
问题描述
我正在尝试使用 iOS15 的 .focused() 修饰符来使用户能够点击文本字段之外的任何位置以移除焦点。我将脱离以下提供的示例:https ://www.youtube.com/watch?v=GqXVFXnLVH4 。以下是我的非工作尝试:
enum Field {
case textField
case notTextField
}
struct ContentView: View {
@State var textInput = ""
@FocusState var focusState:Field?
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($focusState, equals: .textField)
Rectangle()
.focused($focusState, equals: .notTextField)
.onTapGesture {
state = .notTextField
}
}
}
}
解决方案
我发现解决方案不是聚焦另一个元素,而是将文本字段的焦点切换为 false:
@State var textInput = ""
@FocusState var textFieldIsFocused: Bool
var body: some View {
VStack {
TextField("Enter some text...", text: $textInput)
.focused($textFieldIsFocused)
Rectangle()
.onTapGesture {
textFieldIsFocused = false
}
}
}
推荐阅读
- cassandra - 使用 UDF 和 UDA 在 Cassandra 中实现草图
- python - 使用异常处理防止系统崩溃时出现几行
- python - 从文件中提取 json 对象
- linux - 为什么 AWS 实例只有 16GB 时,`/proc/meminfo` 显示 32GB?
- activemq-artemis - Artemis 对称集群示例
- magento - 如何在 Magento 2 中集中日志
- hyperledger - 我们如何在 Hyperledger Indy 钱包中导入外部创建的密钥对?
- spring-boot - Junit 5 与 Mockito java.lang.NoSuchMethodError org.junit.platform.engine.EngineDiscoveryRequest.getDiscoveryListener()
- pandas - 无法向空数据框添加新值
- spring-mvc - 在多个 spring mvc 应用程序之间共享地图数据的最佳方法是什么?