您的位置:首页 > 产品设计 > UI/UE

UILabel中长文字自动换行方法

2015-12-20 21:43 489 查看

- iOS6.0版本以前:

UILabel *label;
label.text = @"123456789011121231415
1617181920212223232526272829230";
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
//返回的resize,UILabel中的文字根据CGSizeMake产生的size产生适配的新size
CGSize resize = [label sizeThatFits:CGSizeMake(label.frame.size.width, MAXFLOAT)];
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, size.height);


这种方法在iOS5,6都有效,在iOS6以后被desperate

- iOS6.0版本以上

需要用到以下方法:返回文本占据的矩形区域

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);


参数:

size
:需要绘制的矩形大小

options


enum {
NSStringDrawingTruncatesLastVisibleLine = 1 << 5,
NSStringDrawingUsesLineFragmentOrigin = 1 << 0,
NSStringDrawingUsesFontLeading = 1 << 1,
NSStringDrawingUsesDeviceMetrics = 1 << 3,
};
typedef NSInteger NSStringDrawingOptions;


NSStringDrawingTruncatesLastVisibleLine
: 如果文本内容比指定的尺寸要大,哪个最后可见的那行,会被截断,并且添加省略号。如果没有同时设置NSStringDrawingUsesLineFragmentOrigin那么这个选项的设置会被忽略。

(Truncate and add an ellipsis character to the last visible line if the text does not fit into the specified bounds. This option is ignored if the NSStringDrawingUsesLineFragmentOrigin option is not also specified.)

NSStringDrawingUsesLineFragmentOrigin
:默认绘制String的设置是“the line fragment origin”(自动换行),而不是一行的显示的。

(The origin specified when drawing the string is the line fragment origin and not the baseline origin.)

NSStringDrawingUsesFontLeading
:运用字体大小来计算行高

(Use the font leading information to calculate line heights.)

NSStringDrawingUsesDeviceMetrics
:使用图像字形边界(而不是排版的界限)计算布局。(Use the image glyph bounds (instead of the typographic bounds) when computing layout.)

attributes
:应用于String的一些属性,对于NSAttributedString这些属性同样适用,但是对于NSString而言这些设置的属性是对于整个字符串的,而不是某个范围的。

context
:context上下文。包括一些信息,例如如何调整字间距以及缩放。最终,该对象包含的信息将用于文本绘制。该参数可为 nil 。

最近项目中用到的代码

#import "UILabel+Common.h"

@implementation UILabel (Common)
- (void)setLongString:(NSString *)str withFitWidth:(CGFloat)width {
[self setLongString:str withFitWidth:width withMaxHeight:MAXFLOAT];
a0fc
}

- (void)setLongString:(NSString *)str withFitWidth:(CGFloat)width withMaxHeight:(CGFloat)maxHeight {
self.numberOfLines = 0;
CGSize size = CGSizeMake(width, MAXFLOAT);

CGRect textRect = [str boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName : self.font}
context:nil];
CGRect rect = self.frame;
rect.size.height = textRect.size.height;
self.frame = rect;
self.text = str; //注意这个从新赋值,之前没有赋值出现Label尺寸有变换,但是文字任然是一行显示的问题,
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: