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

查看:466
本文介绍了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")
}

推荐答案

最新

已经指出,自SwiftUI 2起,此功能不再有效,因此根据您所使用的版本,这可能不再是正确的答案

It has been pointed out that since SwiftUI 2, this no longer works, so depending on the version you're using, this may no longer be the correct answer

原始答案:

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天全站免登陆