label的字体与行间距的设置一定要和计算方法中label和行间距的设置一直,出错通常都是这两个因素
label设置了属性字符串,所有对字符串的修改都要在属性字符串中修改,不然会被覆盖
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setLineSpacing:6];
CGSize brandDescribeLableSize = [brandGoods.model_name sizeWithMaxWidth:maxMargin addributes:@{NSParagraphStyleAttributeName:paragraphStyle1,NSFontAttributeName:brandTitleFont}];
// 设置label字符串的高度和位置
- (void)setText:(NSString *)text spaceHeight:(CGFloat)spaceHeight textAlignment:(LabelPosion)position
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:spaceHeight];//调整行间距
[paragraphStyle setLineBreakMode:NSLineBreakByTruncatingTail];
if (position == LabelPosionLeft) {
[paragraphStyle setAlignment:NSTextAlignmentLeft];
}else if (position == LabelPosionRight){
[paragraphStyle setAlignment:NSTextAlignmentRight];
}else if (position == LabelPosionCenter){
[paragraphStyle setAlignment:NSTextAlignmentCenter];
}
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
self.attributedText = attributedString;
}
// 限制label的行数
- (CGSize)setLines:(NSInteger)lines andText:(NSString *)text LineSpacing:(CGFloat)lineSpacing withWidth:(CGFloat)width
{
self.numberOfLines = lines;
CGFloat oneRowHeight = [text sizeWithAttributes:@{NSFontAttributeName:self.font}].height;
CGSize textSize = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size;
//设置文字的属性
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpacing];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
//计算出真实大小
CGFloat rows = textSize.height / oneRowHeight;
CGFloat realHeight;
if (rows >= lines) {
rows = lines;
}
realHeight = (rows * oneRowHeight) + (rows - 1) * lineSpacing;
[self setAttributedText:attributedString];
return CGSizeMake(textSize.width, realHeight);
}
总结:paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
[paragraphStyle setAlignment:NSTextAlignmentCenter
这些属性都需要在属性字符串中设置