Joseph Francis
Joseph Francis

Reputation: 1231

A String extension to determine the width of the String dynamically?

I have a String in a variable called text. I want to figure out the width of this text 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#>)
        
}
}  

Upvotes: 15

Views: 9502

Answers (1)

David Chopin
David Chopin

Reputation: 3064

This extension to String requires UIKit and determines 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))

Upvotes: 33

Related Questions