iOS文字排版问题总结

1、UILabel行间距问题:设计师要求UILabel要有行间距,但是UILabel是没有这么一个直接暴露的属性的,想要修改lineSpacing,我们需要借助NSAttributedString来实现,需要注意计算文字上下留白,示意代码:

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];
或者可以创建一个重新实现[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 方法。

你可能感兴趣的:(iOS文字排版问题总结)