【问题标题】:What can I use in place of Text View in Swift UI?我可以在 Swift UI 中使用什么来代替 Text View?
【发布时间】:2019-10-12 13:29:21
【问题描述】:

我希望有一个最大字符数限制的可编辑文本字段,就像推文一样,但我在 SwiftUI 中没有找到解决方案。有没有人找到解决这个问题的方法?

【问题讨论】:

  • 嗨,Erim,欢迎来到 SO。您的问题需要与项目的特定部分有关。不仅仅是一般的钓鱼探险。

标签: swift swiftui swift5 swift5.1 swift5.2


【解决方案1】:

您需要的是TextField,您必须使用数据模型来限制最大字符数,如this answer 中所述。

【讨论】:

    【解决方案2】:

    我找到了您问题的答案。

    此解决方案不使用 EnvironmentObject。

    请检查此页面。 How to use Combine on a SwiftUI View

    这是我的示例代码。

    import SwiftUI
    import Combine
    struct ContentView: View {
        @ObservedObject private var restrictInput = RestrictInput(5)
        var body: some View {
            Form {
                TextField("input text", text: $restrictInput.text)
            }
        }
    }
    
    // https://stackoverflow.com/questions/57922766/how-to-use-combine-on-a-swiftui-view
    class RestrictInput: ObservableObject {
        @Published var text = ""
        private var canc: AnyCancellable!
        init (_ maxLength: Int) {
            canc = $text
                .debounce(for: 0.5, scheduler: DispatchQueue.main)
                .map { String($0.prefix(maxLength)) }
                .assign(to: \.text, on: self)
        }
        deinit {
            canc.cancel()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多