• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SwiftUI TextField 最大长度

用户头像
it1352
帮助1

问题说明

是否可以为 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")
}

正确答案

#1

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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfakah
系列文章
更多 icon
同类精品
更多 icon
继续加载