11

Let's say I have a text called: This. I want to figure out the width of the text called This so that I can assign a width to another view's frame. How do I go about it?

struct BadgeTextView: View {

var text: String

var body: some View {
    Rectangle()
        .fill(Color.red)
    .cornerRadius(3)
        .frame(width: text.???, height: <#T##CGFloat?#>, alignment: <#T##Alignment#>)

}
}  
Joseph Francis
  • 1,111
  • 1
  • 15
  • 26
  • 1
    "Width" is not an intrinsic property of a string. Figuring out the width of a string requires a font and a font size. Just make sure you consider that as well. – Sweeper Nov 09 '19 at 18:34

1 Answers1

25

This extension to String should build on Sweeper's suggestion to let you get the width of a String given a certain font:

extension String {
   func widthOfString(usingFont font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttributes)
        return size.width
    }
}

This would be used like so: let width = "SomeString".widthOfString(usingFont: UIFont.systemFont(ofSize: 17, weight: .bold))

David Chopin
  • 2,780
  • 2
  • 19
  • 40
  • 2
    That is so brilliant! I was messing with GeometryReady and preference(key:value:) without success. – Atsuo Sakakihara Aug 11 '20 at 17:00
  • 1
    I am using Courier because it is monospaced. The width of a string with "1" repeated 36 times is 257.34375, while a string with 36 "M"s is 492.1875. Because it is monospaced, shouldn't these widths be identical? – Greg Aug 19 '20 at 18:16