【问题标题】:SwiftUI display characters count remaining in a label/textSwiftUI 显示标签/文本中剩余的字符数
【发布时间】:2020-05-01 01:04:08
【问题描述】:

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

我可以在 Swift 和 Storyboard 中轻松做到这一点,但我不确定如何在 SwiftUI 中做到这一点?

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

这是我的观点的代码:

    Section(header: Text("Additional Information")) {

        MultilineTextView(text: $notes)


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

    }

这总是显示零 (0)

【问题讨论】:

  • 很难想象你在MultilineTextView 中使用绑定做了什么。你会显示代码吗?

标签: ios swiftui


【解决方案1】:

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

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() 改进您的用户界面我不知道您想如何显示它,所以我只是以您为例。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多