简体   繁体   English

如何获取 NSString 的大小

[英]How to get the size of a NSString

A "quicky": how can I get the size (width) of a NSString? “快速”:如何获得 NSString 的大小(宽度)?

I'm trying to see if the string width of a string to see if it is bigger than a given width of screen, case in which I have to "crop" it and append it with "...", getting the usual behavior of a UILabel.我正在尝试查看字符串的字符串宽度是否大于给定的屏幕宽度,在这种情况下我必须“裁剪”它并附加“...”,获得通常的行为一个 UILabel。 string.length won't do the trick since AAAAAAAA and iiiiii have the same length but different sizes (for example). string.length 不会起作用,因为 AAAAAAAA 和 iiiiii 具有相同的长度但大小不同(例如)。

I'm kind of stuck.我有点卡住了。

Thanks a lot.非常感谢。

This is a different approach.这是一种不同的方法。 Find out the minimum size of the text so that it won't wrap to more than one line.找出文本的最小大小,以便它不会换行超过一行。 If it wraps to over one line, you can find out using the height.如果它包装到超过一行,您可以使用高度找出。

You can use this code:您可以使用此代码:

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont 
                           constrainedToSize:maximumSize 
                               lineBreakMode:self.myLabel.lineBreakMode];

300 is the width of the screen with a little space for margins. 300 是屏幕的宽度,有一点空白空间。 You should substitute your own values for font and size, and for the lineBreakMode if you're not using IB.如果您不使用 IB,您应该替换您自己的字体和大小值,以及lineBreakMode

Now myStringSize will contain a height which you can check against the height of something you know is only 1 line high (using the same font and size).现在myStringSize将包含一个height ,您可以根据您知道只有 1 行高的东西的高度(使用相同的字体和大小)来检查该高度。 If it's bigger, you'll need to cut the text.如果它更大,则需要剪切文本。 Note that you should add a ... to the string before you check it again (adding the ... might push it over the limit again).请注意,在再次检查之前,您应该在字符串中添加一个 ...(添加 ... 可能会再次超过限制)。

Put this code in a loop to cut the text, then check again for the correct height.将此代码放入循环中以剪切文本,然后再次检查正确的高度。

Use below method.使用下面的方法。

Objective-C目标-C

- (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
    }
    return size;
}

Swift 3.0斯威夫特 3.0

func findHeight(forText text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize {
    var size = CGSizeZero
    if text {
        var frame = text.boundingRect(withSize: CGSize(width: widthValue, height: CGFLOAT_MAX), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        size = CGSize(width: frame.size.width, height: frame.size.height + 1)
    }
    return size
}

You need to use Core Graphics to measure the string, as rendered in your specified font and size.您需要使用 Core Graphics 来测量以您指定的字体和大小呈现的字符串。 See the answers to Measuring the pixel width of a string for a walkthrough.有关演练,请参阅测量字符串的像素宽度的答案。

sizeWithFont:constrainedToSize:lineBreakMode 

is deprecated now.现在已弃用。 Use below code snippet,使用下面的代码片段,

UIFont *font=[UIFont fontWithName:@"Arial" size:16.f];

NSString *name = @"APPLE";

CGSize size = [name sizeWithAttributes:@{NSFontAttributeName:font}];

For whatever its worth --- I think the OP takes the wrong way to get there... if the measurement of width only serves to find the place where text should be clipped, and followed by ellipsis --- then OP should be aware of that this facility is implemented in all Text Views in Cocoa...不管它的价值——我认为 OP 采取了错误的方式到达那里......如果宽度的测量仅用于找到应该剪切文本的位置,然后是省略号——那么 OP 应该意识到这个工具在 Cocoa 的所有文本视图中实现......

Pay attention to this enumeration:注意这个枚举:

typedef NS_ENUM(NSUInteger, NSLineBreakMode) {
    NSLineBreakByWordWrapping = 0,         // Wrap at word boundaries, default
    NSLineBreakByCharWrapping,        // Wrap at character boundaries
    NSLineBreakByClipping,        // Simply clip
    NSLineBreakByTruncatingHead,    // Truncate at head of line: "...wxyz"
    NSLineBreakByTruncatingTail,    // Truncate at tail of line: "abcd..."
    NSLineBreakByTruncatingMiddle    // Truncate middle of line:  "ab...yz"
} API_AVAILABLE(macos(10.0), ios(6.0), watchos(2.0), tvos(9.0));

By setting the line breaking mode of your text-field or text view to NSLineBreakByTruncatingTail , you'll achieve what you want, and probably at higher quality, without implementing yourself.通过将文本字段或文本视图的换行模式设置为NSLineBreakByTruncatingTail ,您将实现您想要的,并且可能以更高的质量实现,而无需您自己实现。

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

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