SwiftUI显示标签/文本中剩余的字符数



我有UITextView,我想向用户显示当前字符数?

我可以在swift和故事板中轻松做到这一点,但我不确定如何在SwiftUI中做到这一步?

我如何获得标签/文本的"引用",该标签/文本将保存并向用户显示字符数?

以下是我的观点代码:

Section(header: Text("Additional Information")) {
MultilineTextView(text: $notes)

Text("(String(notes.count))") 
}

这总是显示零(0(

我需要类似的东西,所以我得到了绑定类的扩展

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)
}
)
}
}

这将允许侦听绑定上的更改

现在是简单的部分,获取计数并显示

@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
}

你可以使用ZStackVStackHStackSpacer()来改进你的UI。我不知道你想如何显示它,所以我只是举了你的例子。

此外,如果它是一个简单的函数,例如count,你不需要声明一个函数,你可以像一样在闭包中写它

// ...
MultilineTextView(text: $notes.didSet(execute: { (value: String) in self.charCount = value.count }))

最新更新