UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Text: Counting Number of Elements from LocalizedStringKey with SF Symbols

Forums > 100 Days of SwiftUI

Hello!

I am trying to create a custom text view and want to be able to use SF Symbols with it. I am aware of text elements in SwiftUI being able to take a LocalizedStringKey, and how you can interpolate certain accepted things into one. In my specific case, I want to interpolate an SF Symbol in a text element:

Text("CAMERA \(Image(systemName: "camera"))")

This should display the word "CAMERA" with a camera SF Symbol next to it.

My problem is that I need to count the number of elements in this text element, but not the literal value passed in. Rather, I want to count the number of elements from how it is displayed. So, I would count the number of characters in "CAMERA" (which is six) and then count the space next to it (which is one), then the SF Symbol as another character (which is of course one). Then, the total number of characters in my original text element would be eight.

Basically, I need to be able to count the number of characters in a LocalizedStringKey and count symbols as one character. LocalizedStringKey does not have a .count member, so I need to figure out a way to do this by myself.

To be crystal clear, my goal is to have behavior similar to how Swift counts the characters in a string with emojis:

let string = "CAMERA 📸"
print(string.count) // 8

I want this to work for SF Symbols in a text element though. Any help/clarification? Thanks! :)

2      

Unlike an emoji, which is unicode text, a SF Symbol is a vector graphic and not text. So you can't count it like an emoji.

You could use Label instead of Text, though. https://www.hackingwithswift.com/articles/237/complete-guide-to-sf-symbols

2      

Hi,

You could try to replace the SF Symbol with a space or any other character and then count that,

let string = "camera \(Image(systemName: "camera"))"
print(string.replacing(/Image(.+?)\)/, with: " ").count)

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.