I would like to have an editable text field with max number of characters limit, just like a tweet, but I didn't find a solution in SwiftUI for this. Has anyone found a solution to this problem?
Asked
Active
Viewed 170 times
-2
-
Hi Erim, welcome to SO. Your question needs to be about a specific piece of your project. Not just a general fishing expedition. – Warren Burton Oct 12 '19 at 13:39
2 Answers
1
What you need is TextField, you have to use data model to restrict max number of characters as described in this answer.

user158
- 12,852
- 7
- 62
- 94
0
I found the answer to your question.
This solution don't use EnvironmentObject.
Please check this page. How to use Combine on a SwiftUI View
this is my sample code.
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()
}
}

Masanao Imai
- 125
- 2
- 2