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

查看:119
本文介绍了如何获得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天全站免登陆