SwiftUI - Create char counter to check number of characters with spaces| Apple iOS Xcode YouTube Seminar #19


Swift5.1.3 Xcode11.3.1 SwiftUI


- How to create character length counter
- Study the function of TextArea and String
- You can add it with SwiftUI


Character length counter for word count with spaces


* Here is the highlight of YouTube tutorial.

You may sometimes like to know the length of characters when you post your comment at some services like Twitter. It has the limit of 280 letters. Does the apple official notes work well for the draft?

If the answer is no, you should create it by yourself. It's not so difficult. Just copy-and-paste of my code works after all.

But, if you can understand the meaning of code, you can develop more functional app for future so let's study the basic for now.

First, you need to create struct named TextArea with the protocol, UIViewRepresentable.


struct TextArea: UIViewRepresentable {
@Binding var text: String

func makeUIView(context: Context) -> UITextView {

let myTextArea = UITextView()
myTextArea.delegate = context.coordinator
myTextArea.font = UIFont(name: "HelveticaNeue", size: 25)
myTextArea.backgroundColor = UIColor(displayP3Red: 0.8, green: 0.8, blue: 0.0, alpha: 0.2)

return myTextArea
}

func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

class Coordinator : NSObject, UITextViewDelegate {

var parent: TextArea

init(_ uiTextView: TextArea) {
self.parent = uiTextView
}

func textViewDidChange(_ textView: UITextView) {
self.parent.text = textView.text
}
}
}



The function named makeUIView() determine the design of text area. It takes a role of font size, text format and color of area. The class Coordinator input the text information and reflect the string data. The variable "text" will have the typed string.

To delete all strings, you can use the "reset" button with the following code.


@State var text = ""

var body: some View {
VStack {

HStack {
Button(action: {
self.text = ""
}) {
Text("Reset")
}
Spacer().frame(width:50)

Text("Char Count: \(text.count)")
}

TextArea(
text: $text
).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}

}



To show the number of characters for the typed text, use the following code.


Text("Char Count: \(text.count)")



Just add "count" with dot and you can calculate the length of string. The type of value will be "Int" so you need to convert it into String to confirm the number visually in text.


To get the source code, check the comment of my YouTube

Back to Table List

2020年02月07日