Foundation-几种段落排版格式NSMutableParagraphStyle

时间:2023-02-01 07:52:13

一、框架中的原始定义如下:

@property(readwrite)CGFloat lineSpacing;        //行间距
@property(readwrite)CGFloat paragraphSpacing; //段落间距
@property(readwrite)NSTextAlignment alignment; //文字对齐格式
@property(readwrite)CGFloat firstLineHeadIndent; //首行缩进
@property(readwrite)CGFloat headIndent; //行首缩进
@property(readwrite)CGFloat tailIndent; //行尾缩进
@property(readwrite)NSLineBreakMode lineBreakMode;//段落文字溢出隐藏方式
@property(readwrite)CGFloat minimumLineHeight; //最小行高
@property(readwrite)CGFloat maximumLineHeight; //最大行高
@property(readwrite)NSWritingDirection baseWritingDirection;//段落书写方向
@property(readwrite)CGFloat lineHeightMultiple; //多行行高
@property(readwrite)CGFloat paragraphSpacingBefore;//段落前间距
@property(readwrite)float hyphenationFactor; //英文断字连字符

二、NSTextAlignment文字对齐方式枚举(IOS6以上有效)

NSTextAlignmentLeft     //居左

NSTextAlignmentRight    //居右

NSTextAlignmentCenter   //居中

NSTextAlignmentNatural   //默认

NSTextAlignmentJustified //自调整


三、NSWritingDirection文字书写方向(IOS6以上有效):

NSWritingDirectionNatural     //使用Bidi算法规则P2和P3定义方向

NSWritingDirectionLeftToRight //从左向右

NSWritingDirectionRightToLeft  //从右向左


示例源码:

NSString*text=@"秋叶黄,秋叶黄,我深深的沉醉其中,摇摆的叶片,枯黄着也是秋天,飘落着也是秋天;秋叶黄,秋叶黄,你随风悄悄的散去,枯萎的树枝,下着雨也是秋天,吹着风也是秋天.";

//就用这两个options枚举参数吧,我也不知道为啥
NSStringDrawingOptions options =NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading;
// labelW是段落的固定宽度;CGFLOAT_MAX固定用这个;attributes按照下面的语句fontSize是字体的大小
// >IOS7
CGFloat labelH = [textboundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX)options:options attributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize]} context:nil].size.height;
//
//CGFloat labelH = [text sizeWithFont:[UIFontsystemFontOfSize:fontSize] constrainedToSize:CGSizeMake(labelW,CGFLOAT_MAX)].height;
//打印计算的高度看一下
NSLog(@"文字段落高度为:%f",labelH);
//实际行数
NSInteger lineNum = labelH/fontSize;

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc ] init];
//文字对齐方式
paragraphStyle.alignment =NSTextAlignmentJustified;
//段落首字符缩进两个字
paragraphStyle.firstLineHeadIndent =2*fontSize;
//行间距
paragraphStyle.lineSpacing =lingSpace;
//属性字典,包括前景字体颜色和段落属性
NSDictionary *attributes =@{NSForegroundColorAttributeName:[UIColorredColor],NSParagraphStyleAttributeName:paragraphStyle};
//属性字符串
NSAttributedString *attributedText = [[NSAttributedString alloc ] initWithString : text attributes:attributes];

UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 70, 300,labelH+lineNum*lingSpace)];
//文字行数设置为0
label1.numberOfLines = 0;
// label背景色
label1.backgroundColor = [UIColorgreenColor];
label1.attributedText =attributedText;
//显示label

[self.view addSubview:label1];
Foundation-几种段落排版格式NSMutableParagraphStyle