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

后端 未结 4 1238
后悔当初
后悔当初 2021-01-05 00:09

In my application I need to set Read more into the text view if text input is large.so my approach is to find the range of string that would fit in the text view and append

4条回答
  •  感动是毒
    2021-01-05 00:53

    A rough swift translation of kgaidis's excellent answer.

    extension UILabel {
    
        func numberOfCharactersThatFitLabel() -> Int {
            let fontRef = CTFontCreateWithName(self.font.fontName as CFStringRef, self.font.pointSize, nil)
            let attributes = NSDictionary(dictionary: [kCTFontAttributeName : fontRef])
            let attributeString = NSAttributedString(string: text!, attributes: attributes as? [String : AnyObject])
            let frameSetterRef = CTFramesetterCreateWithAttributedString(attributeString as CFAttributedStringRef)
    
            var characterFitRange:CFRange
    
            CTFramesetterSuggestFrameSizeWithConstraints(frameSetterRef, CFRangeMake(0, 0), nil, CGSizeMake(bounds.size.width, CGFloat(numberOfLines)*font.lineHeight), &characterFitRange)
    
            return characterFitRange.length
        }
    }
    

提交回复
热议问题