iOS文字排版問題總結

1、UILabel行間距問題:設計師要求UILabel要有行間距,但是UILabel是沒有這么一個直接暴露的屬性的,想要修改lineSpacing,我們需要借助NSAttributedString來實現(xiàn),需要注意計算文字上下留白,示意代碼:

NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.lineSpacing = 10 - (label.font.lineHeight - label.font.pointSize);
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
label.attributedText = [[NSAttributedString alloc] initWithString:label.text attributes:attributes];

2、UILabel內邊距問題:自定義UILabel,然后重寫drawTextInRect,示意代碼:

import "CustomLabel.h"

@implementation CustomLabel

  • (instancetype)initWithFrame: (CGRect)frame {
    if (self = [super initWithFrame: frame]) {
    _textInsets = UIEdgeInsetsZero;
    }
    }
  • (void)drawTextInRect: (CGRect)rect {
    [super drawTextInRect: UIEdgeInsetsInsetRect(rect, _textInsets)];
    }
    @end

3、YYLabel、YYText

4、UITextView行間距問題,光標問題:

可以使用,
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 15; // <--- indention if you need it
paragraphStyle.firstLineHeadIndent = 15;
paragraphStyle.lineSpacing = 7; // <--- magic line spacing here!
NSDictionary *attrsDictionary =
@{ NSParagraphStyleAttributeName: paragraphStyle }; // <-- there are many more attrs, e.g NSFontAttributeName
self.textView.attributedText = [[NSAttributedString alloc] initWithString:@"Hello World over many lines!" attributes:attrsDictionary];
或者可以創(chuàng)建一個重新實現(xiàn)[UITextView styleString]的子類:
@implementation MBTextView

  • (id)styleString {
    return [[super styleString] stringByAppendingString:@"; line-height: 1.2em"];
    }
    @end

5、字間距問題:

NSString *labelText = label.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(space)}];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
label.attributedText = attributedString;
[label sizeToFit];

6、行高計算:

使用 string.boundingRect 方法。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容