Created
July 23, 2020 01:09
-
-
Save a7mdDev/1a9ec04d6c7976c30df0b7987c8a6a60 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| func willTruncate(text: String, font: UIFont, lineSpacing: CGFloat, maxNumberOfLines: Int, availableWidth: CGFloat) -> Bool { | |
| let paragraph = NSMutableParagraphStyle() | |
| paragraph.lineSpacing = lineSpacing | |
| let sizeThatFits = text.boundingRect(with: CGSize(width: availableWidth, height: .greatestFiniteMagnitude), | |
| options: .usesLineFragmentOrigin, | |
| attributes: [.font: font, .paragraphStyle: paragraph], | |
| context: nil) | |
| let height = sizeThatFits.height | |
| let numberOfLines = Int(round(height / (font.lineHeight + lineSpacing))) | |
| return numberOfLines > maxNumberOfLines | |
| } | |
| let str = "Hello, world!" | |
| willTruncate(text: str, font: .systemFont(ofSize: 12), lineSpacing: 5, maxNumberOfLines: 1, availableWidth: 100) // false | |
| willTruncate(text: str+str, font: .systemFont(ofSize: 12), lineSpacing: 5, maxNumberOfLines: 1, availableWidth: 100) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment