-2

I want to find number of characters that can be displayed on single line of UILabel

I have width of single line

  • The number of characters that fits your width depends on the characters ... a "w" is much bigger than a "l". Without knowing the string, thats kinda impossible to tell. – MartinM Sep 03 '19 at 13:36
  • you can add characters by one to label and check number of lines on each loop – Alexandr Kolesnik Sep 03 '19 at 14:17
  • The reason I asked this question is that, when we add "...see more " at the end of the UILabel. How we do it? What If I want to add it at the end of the 3rd line, only If the text exceeds the 3 lines. – Vinod Kumar Singh Sep 04 '19 at 06:15

3 Answers3

0

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.

Miknash
  • 7,888
  • 3
  • 34
  • 46
0

Try this Find the number of characters that fits in a UITextView with constant width and height with a given string?

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)
} 
Jiffin
  • 405
  • 5
  • 8
-1

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.

cloned
  • 6,346
  • 4
  • 26
  • 38