
-
設置行間距的方式
例如設置 label 的行間距為 10,通常我們會設置 NSAttributedString.lineSpacing = 10 。如下圖左側所示。然而 UI 要求的是右側的效果。通過對比發(fā)現(xiàn),單純設置 NSAttributedString.lineSpacing ,會使得行間距要大于10。
行間距對比
原因如下圖所示,文字的上下均有留白(藍色與紅色重疊的部分)。NSAttributedString.lineSpacing 是下圖綠色的部分,而 UI 設計師想要的是藍色的部分。因此要達到上圖中右側部分需要將下圖重疊的部分減去即可。
實質(zhì)
NSMutableParagraphStyle *rightLabelPragraphStyle = [NSMutableParagraphStyle new];
rightLabelPragraphStyle.lineSpacing = 10 - (self.rightLabel.font.lineHeight - self.rightLabel.font.pointSize);
NSMutableDictionary *RightLabelAttribute = [NSMutableDictionary dictionary];
[RightLabelAttribute setObject:rightLabelPragraphStyle forKey:NSParagraphStyleAttributeName];
self.rightLabel.attributedText = [[NSAttributedString alloc] initWithString:labelStr attributes:RightLabelAttribute];
備注:當文本是單行時,文字底部會多出 lineSpacing 的情況(如下圖所示),因此需要判斷文本為單行時,不設置 lineSpacing

單行文本的情況
- 設置行高的方式
設置 NSAttributedString.maximumLineHeight 與 .minimumLineHeight ,可以精確控制文本行的高度。然后利用 baselineOffset 修復為此帶來的偏移,修復公式: (lineHeight - self.bottomLabel.font.lineHeight)/4。
NSMutableParagraphStyle *bottomParagraphStyle = [NSMutableParagraphStyle new];
bottomParagraphStyle.maximumLineHeight = lineHeight;
bottomParagraphStyle.minimumLineHeight = lineHeight;
NSMutableDictionary *bottomAttributes = [NSMutableDictionary dictionary];
bottomAttributes[NSParagraphStyleAttributeName] = bottomParagraphStyle;
CGFloat baselineOffset = (lineHeight - self.bottomLabel.font.lineHeight)/4;
bottomAttributes[NSBaselineOffsetAttributeName] = @(baselineOffset);
self.bottomLabel.attributedText = [[NSAttributedString alloc] initWithString:labelStr attributes:bottomAttributes];
備注:如果在設置 baselineOffset 的同時設置 range 范圍的背景色或者前景色時,修復公式變?yōu)?(lineHeight - self.bottomLabel.font.lineHeight)/2 ,并且 label 中文本其實位置出錯如圖所示,具體原因暫時未知。


