TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.