How to calculate the width of a text string of a specific font and font-size?

Since sizeWithFont is deprecated, I’m just going to update my original answer to using Swift 4 and .size

//: Playground - noun: a place where people can play
    
import UIKit
           
if let font = UIFont(name: "Helvetica", size: 24) {
   let fontAttributes = [NSAttributedString.Key.font.font: font]
   let text = "Your Text Here"
   let size = (text as NSString).size(withAttributes: fontAttributes)
}

The size should be the onscreen size of “Your Text Here” in points.

Leave a Comment