我有固定的标签,我希望找到可以容纳在标签中的字符数。我认为做好扩展UILabel并编写方法
尝试此扩展程序:
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
}
}