I have UITextView which I would like to display the current character count to the user?
I can easily do this in swift and storyboards, but I an unsure how to do so in
I needed something similar so I got this extension for the Binding class
extension Binding {
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
let snapshot = self.wrappedValue
self.wrappedValue = $0
execute(snapshot)
}
)
}
}
This will allow to listen to changes on bindings
Now comes the easy part, getting the count and showing it
@State var charCount: Int
// code until this section
Section(header: Text("Additional Information")) {
MultilineTextView(text: $notes.didSet(execute: { (value: String) in self.countLeft(value) }))
Text("\(String(charCount))")
}
// outside the body
func getCount(_ value: String) {
self.charCount = value.count
}
You can improve your UI using ZStack
, VStack
, HStack
and Spacer()
I can not figure out how do you want to display it so I just took your example.
Also, if it's a simple function, for example a count, you don't need to declare a function you can write it in the closure like so
// ...
MultilineTextView(text: $notes.didSet(execute: { (value: String) in self.charCount = value.count }))