I want to find number of characters that can be displayed on single line of UILabel
I have width of single line
I want to find number of characters that can be displayed on single line of UILabel
I have width of single line
You can use
func getWidthFor(title: String) -> CGFloat {
let font = UIFont(name: "YourFont", size: 13.0)
let fontAttributes = [NSAttributedString.Key.font: font]
let size = title.size(withAttributes: fontAttributes as [NSAttributedString.Key: Any])
return size.width
}
And then either send on character as a string, or send whole text and check if it fits.
func numberOfCharactersThatFitLabel() -> Int {
// Create an 'CTFramesetterRef' from an attributed string
let fontRef = CTFontCreateWithName(font.fontName as CFString?, font.pointSize, nil)
var attributes: [AnyHashable : Any]? = nil
if let fontRef = fontRef {
attributes = [kCTFontAttributeName : fontRef]
}
let attributedString = NSAttributedString(string: text, attributes: attributes as? [NSAttributedString.Key : Any])
let frameSetterRef = CTFramesetterCreateWithAttributedString(attributedString as CFAttributedString?)
// Get a suggested character count that would fit the attributed string
var characterFitRange: CFRange
CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0, 0), nil, CGSize(width: bounds.size.width, height: CGFloat(numberOfLines) * font.lineHeight), &characterFitRange)
return Int(characterFitRange.length)
}
In objective-C you can estimate it not exactly, but there is a work around: Get specific letter in string and determine letter size. Using UILabel frame width you can calculate average number of characters which can be displayed in single line.
NSString *letter = [label.text substringWithRange:NSMakeRange(index, 1)];
CGSize letterSize = [letter sizeWithFont:self.font];
NSNumber* numberOfCharacters = UILabel.frame.Size.width / letterSize;
if it can help you. Also it will work accurate if you have used monospaced font.