ios开发之--NSMutableParagraphStyle与NSParagraphStyle的使用

时间:2022-06-11 19:56:15

在ios6以后,苹果官方建议用“- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(nullable NSDictionary<NSString *, id> *)attributes context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 7_0);”这个方法进行文本的自适应,也就是动态的计算行高,但是在实际的操作中可能会遇到一些小问题,例如怎么首行索引,在文本里面打空格虽然也能实现,但是并不好控制,还有单纯使用这个方法的话,必须看设置Attributes,才能实现;行高,行间距等小问题!以前并没有遇到过,如果要实现这种精确操作的话,可以使用NSMutableParagraphStyle来实现,

下面就来介绍下这个属性的具体属性和用法:

    //   NSParagraphStyleAttributeName 段落的风格(设置首行,行间距,对齐方式什么的)看自己需要什么属性,写什么
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = ;// 字体的行间距
paragraphStyle.firstLineHeadIndent = 20.0f;//首行缩进
paragraphStyle.alignment = NSTextAlignmentJustified;//(两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然)
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz")
paragraphStyle.headIndent = ;//整体缩进(首行除外)
paragraphStyle.tailIndent = ;//
paragraphStyle.minimumLineHeight = ;//最低行高
paragraphStyle.maximumLineHeight = ;//最大行高
paragraphStyle.paragraphSpacing = ;//段与段之间的间距
paragraphStyle.paragraphSpacingBefore = 22.0f;//段首行空白空间/* Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */
paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;//从左到右的书写方向(一共➡️三种)
paragraphStyle.lineHeightMultiple = ;/* Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */
paragraphStyle.hyphenationFactor = ;//连字属性 在iOS,唯一支持的值分别为0和1

了解了上面的这些功能后,就可以使用boundingRectWithSize方法对段落的动态高度进行计算了,代码如下:

UILabel *hLab = [[UILabel alloc]initWithFrame:CGRectMake(, , , )];
hLab.numberOfLines = ;
hLab.lineBreakMode = NSLineBreakByWordWrapping;
hLab.text = @"三晋大地,生机盎然。\n6月21日至23日,***在山西省委书记骆惠宁、