简体   繁体   English

UILabel的单个字符的宽度?

[英]Width of Single Character of UILabel?

I want to find number of characters that can be displayed on single line of UILabel我想找到可以在 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.然后要么将字符作为字符串发送,要么发送整个文本并检查它是否合适。

Try this Find the number of characters that fits in a UITextView with constant width and height with a given string?试试这个用给定的字符串找出适合 UITextView 宽度和高度恒定的字符数?

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.在objective-C 中,您可以不准确地估计它,但有一个解决方法:获取字符串中的特定字母并确定字母大小。 Using UILabel frame width you can calculate average number of characters which can be displayed in single line.使用 UILabel 框架宽度,您可以计算可以在单行中显示的平均字符数。

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.如果您使用等宽字体,它也会准确工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM