SwiftUI TextField 最大长度 [英] SwiftUI TextField max length

查看:29
本文介绍了SwiftUI TextField 最大长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为 TextField 设置最大长度?我正在考虑使用 onEditingChanged 事件处理它,但它仅在用户开始/完成编辑时调用,而不是在用户键入时调用.我也阅读了文档,但还没有找到任何东西.有什么解决办法吗?

Is it possible to set a maximum length for TextField? I was thinking of handling it using onEditingChanged event but it is only called when the user begins/finishes editing and not called while user is typing. I've also read the docs but haven't found anything yet. Is there any workaround?

TextField($text, placeholder: Text("Username"), onEditingChanged: { _ in
  print(self.$text)
}) {
  print("Finished editing")
}

推荐答案

Paulw11 的答案的略短版本是:

A slightly shorter version of Paulw11's answer would be:

class TextBindingManager: ObservableObject {
    @Published var text = "" {
        didSet {
            if text.count > characterLimit && oldValue.count <= characterLimit {
                text = oldValue
            }
        }
    }
    let characterLimit: Int

    init(limit: Int = 5){
        characterLimit = limit
    }
}

struct ContentView: View {
    @ObservedObject var textBindingManager = TextBindingManager(limit: 5)
    
    var body: some View {
        TextField("Placeholder", text: $textBindingManager.text)
    }
}

您只需要一个用于 TextField 字符串的 ObservableObject 包装器.将其视为每次发生更改时都会收到通知并能够将修改发送回 TextField 的解释器.但是,无需创建 PassthroughSubject,使用 @Published 修饰符将获得相同的结果,代码更少.

All you need is an ObservableObject wrapper for the TextField string. Think of it as an interpreter that gets notified every time there's a change and is able to send modifications back to the TextField. However, there's no need to create the PassthroughSubject, using the @Published modifier will have the same result, in less code.

有一点,你需要使用didSet,而不是willSet,否则你会陷入递归循环.

One mention, you need to use didSet, and not willSet or you can end up in a recursive loop.

这篇关于SwiftUI TextField 最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆