限制字符或为 SwiftUI 中的 TextField 中的输入提供验证

问题描述 投票:0回答:1

目标:我想限制 SwiftUI TextField 输入最多 3 个字符。

结果:由于某种原因,有一种方法可以在 TextField 中输入超过 3 个字符

步骤:

  1. 在文本字段中输入“123”
  2. 开始多次输入“4”
  3. 您会看到,对于每第三个输入,文本字段内都会有“1234”

其他信息

  • getter
    setter
    打印不打印“1234”输出,这真的很奇怪
  • 请检查下面的gif

问题:如何限制/验证给定示例的 SwiftUI TextField 输入?

游乐场代码:

import SwiftUI
import PlaygroundSupport
import Combine

struct ContentView: View {
    @State var inputValue: String = ""
    @State var previousValue: String = ""

    func getter() -> String {
        print("getter called with ", inputValue)
        return inputValue
    }

    func setter(_ newValue: String) {
        print("setter called with ", inputValue)
        if newValue.count > 3 {
            inputValue = previousValue
        } else {
            inputValue = newValue
            previousValue = inputValue
        }
    }

    var body: some View {
        TextField("", text: .init(get: getter, set: setter))
            .frame(minWidth: 100)
    }
}


PlaygroundPage.current.setLiveView(ContentView())

此外,即使您更新 TextField 定义,例如:

    var body: some View {
        TextField("", text: .init(get: { "test "}, set: { _ in }))
            .frame(minWidth: 100)
    }

要始终强制“测试”值,您仍然可以在每三次尝试中输入附加字符

ios swift swiftui textfield
1个回答
3
投票

这可以使用

.onChange
视图修改器来处理。如果我的语法有点偏差,请抱歉,我的 IDE 无法立即可用。

在 SwiftUI 中,你永远不应该真正使用直接的 getter 和 setter。

  @State var yourText = ""

  var body: some View {
      VStack {
          // Your Text w/ @State Binding
      }
      .onChange(of: yourText) { newValue in 
          // Handle your constraints here. 
          // Check your value, if it exceeds your 3 char
          // reset it back to the limit. 
      }
  }

2023 年更新 | iOS 17+

.onChange
已更改为直接使用闭包内部的
yourText
绑定值,而不是闭包属性。

.onChange(of: yourText) {
    // Handle your constraints here. 
    // Use the `yourText` binding property instead of capturing `newValue`
}
© www.soinside.com 2019 - 2024. All rights reserved.