SwiftUI显示的字符数仍留在标签/文本中 [英] SwiftUI display characters count remaining in a label/text

查看:76
本文介绍了SwiftUI显示的字符数仍留在标签/文本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have UITextView which I would like to display the current character count to the user?

我可以在swift和情节提要中轻松地做到这一点,但是我不确定如何在SwiftUI中做到这一点?

I can easily do this in swift and storyboards, but I an unsure how to do so in SwiftUI?

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

How do I get the "reference" to the label/text which would hold and display the character count to the users?

以下是我的视图代码:

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

        MultilineTextView(text: $notes)


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

    }

这始终显示零(0)

推荐答案

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

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
}

您可以使用ZStackVStackHStackSpacer()来改善UI.我不知道您想如何显示它,所以我仅以您的示例为例.

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

这篇关于SwiftUI显示的字符数仍留在标签/文本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆