如何获取 NSString 的大小 [英] How to get the size of a NSString

查看:21
本文介绍了如何获取 NSString 的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速":如何获取 NSString 的大小(宽度)?

A "quicky": how can I get the size (width) of a NSString?

我正在尝试查看字符串的字符串宽度是否大于给定的屏幕宽度,在这种情况下我必须裁剪"它并附加...",得到UILabel 的通常行为.string.length 不会起作用,因为 AAAAAAAA 和 iiiiii 具有相同的长度但大小不同(例如).

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. string.length won't do the trick since AAAAAAAA and iiiiii have the same length but different sizes (for example).

我有点卡住了.

非常感谢.

推荐答案

这是一种不同的方法.找出文本的最小大小,以便它不会换行超过一行.如果它换行超过一行,您可以使用高度找出.

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.

您可以使用此代码:

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 是屏幕的宽度,留有一点空白空间.如果你不使用 IB,你应该用你自己的字体和大小值代替 lineBreakMode.

300 is the width of the screen with a little space for margins. You should substitute your own values for font and size, and for the lineBreakMode if you're not using IB.

现在 myStringSize 将包含一个 height,您可以检查它的高度,您知道它只有 1 行高(使用相同的字体和大小).如果它更大,则需要剪切文本.请注意,在再次检查之前,您应该在字符串中添加一个 ...(添加 ... 可能会再次超过限制).

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). 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.

这篇关于如何获取 NSString 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆