I translated the answer from this ObjC question into Swift; what may be tripping you up is that you need to cast String
to NSString
.
Swift 4
let text = "Hello"
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let maxSize = CGSize(width: 100, height: CGFloat.greatestFiniteMagnitude)
let size = (text as NSString).boundingRect(with: maxSize,
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [NSFontAttributeName:font],
context: nil)
.size
Swift 3
let text = "Hello"
let font = UIFont.systemFontOfSize(UIFont.systemFontSize())
let maxSize = CGSize(width: 100, height: CGFloat.max)
let size = (text as NSString).boundingRectWithSize(maxSize,
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
attributes: [NSFontAttributeName:font],
context: nil)
.size