找出标签中可以容纳的字符数

问题描述 投票:-2回答:1

我有固定的标签,我希望找到可以容纳在标签中的字符数。我认为做好扩展UILabel并编写方法

ios swift label
1个回答
0
投票

尝试此扩展程序:

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.