Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get text length in Swift 4?

Tags:

swift4

uifont

I am not sure how to update this code:

func textWidth(text: String, font: UIFont?) -> CGFloat
{
    let attributes = font?.fontDescriptor.fontAttributes
    return text.size(withAttributes: attributes).width
}

Swift 4 complain: Cannot convert value of type '[UIFontDescriptor.AttributeName : Any]?' to expected argument type '[NSAttributedStringKey : Any]?'

I don't know why they broke this, but it does not get automatically fixed.

like image 443
MarkAurelius Avatar asked Dec 31 '25 10:12

MarkAurelius


1 Answers

(SWIFT 4 Updated)

func textWidth(text: String, font: UIFont?) -> CGFloat {
    let attributes = font != nil ? [NSFontAttributeName: font] : [:]
    return text.size(withAttributes: attributes).width
}

Hope it helps.

like image 81
Avinash Mishra Avatar answered Jan 06 '26 07:01

Avinash Mishra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!