家居万能侠

iOS: UILabel 实现 Markdown 代码框

2017-11-01  本文已影响0人  麦兜菠萝油王子

实现这个我真的花了很长的时间,效果和简书的代码框差不多,因为简书也是采用了 Markdown 的代码框,就像下面这样。

特别喜欢孙燕姿的这张专辑。
克卜勒是以天文学家Johannes Kepler命名的一颗超新星。
是四百年来第一次在白天可以用肉眼看到的星星。
我不太懂那些宇宙的事,因为自己的不够聪明,反而对这个世界格外放心。
太阳每天都会升起来,潮水每天都会退去,“藏在众多孤星之中,还是找得到你”。

—— [来自网易云评论] (http://music.163.com/#/song?id=28196001)

要实现这个效果,相当于要解决下面这几个问题。

一、UILabel 添加边框和背景色

这个是最简单的,没什么好说,直接贴代码,颜色都帮你取好了。

UILabel *label = [[UILabel alloc] init];
label.layer.borderWidth= 1.0f;
label.layer.cornerRadius=5.0f;
label.layer.borderColor = [[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1] CGColor];

二、UILabel 设置文本的行高

NSString *text = @"藏在众多孤星之中\n还是找得到你";

NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:text];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

[style setLineSpacing:lineSpacing];

[attrString addAttribute:NSParagraphStyleAttributeName
                       value:style
                       range:NSMakeRange(0, text.length)];
    
label.attributedText = attrString;

三、UILabel 支持多行文本和动态高度

这里需要设置 label 的相关属性和加上自动布局的水平限制。

[self.view addSubview:label];

label.numberOfLines = 0;
label.translatesAutoresizingMaskIntoConstraints = NO;

NSArray *labelConstraints = nil;
NSDictionary *views = @{
    @"label": label,
};
labelConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[label]-10-|" options:0 metrics:nil views:views];
[self.view addConstraints:labelConstraints];

注:上面都是伪代码,只提供一个大概思路。

四、UILabel 设置 Padding

这个是最难的地方,我在 Stackoverflow 找到下面两个解决方案。

  1. subclass UILabel 并重写 drawTextInRect 和 intrinsicContentSize 方法
  2. 如果只是添加左右 Padding,可以使用 NSAttributedString

很显然我们是需要添加4个方向的 Padding,但当我采用第一种方法时,发现如果文本太长,出现换行的情况下,高度的计算会有问题,部分文本显示不出来。第一种方法只适用于添加上下两个方向的 Padding,不能用于添加左右方向的 Padding。

所以这里必须结合两种方案,才能顺利实现4个方向的 Padding 添加。最后我就直接贴实现的代码好了。

// CodeBlockLabel.h

#import <UIKit/UIKit.h>

@interface CodeBlockLabel : UILabel

- (void)setBlockText:(NSString*)text;
- (void)setBlockText:(NSString*)text fontSize:(NSInteger)fontSize lineSpacing:(NSInteger)lineSpacing;

@end
// CodeBlockLabel.m

#import "CodeBlockLabel.h"

@implementation CodeBlockLabel

float topInset, leftInset, bottomInset, rightInset;

- (instancetype)init {
    if (self = [super init]) {
        [self setContentEdgeInsets:UIEdgeInsetsMake(20, 0, 20, 0)];
        
        self.numberOfLines = 0;
        self.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:1];
        self.translatesAutoresizingMaskIntoConstraints = NO;
        
        self.layer.cornerRadius=5.0f;
        self.layer.borderColor = [[UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1] CGColor];
        self.layer.borderWidth= 1.0f;
    }
    
    return self;
}

- (void)drawTextInRect:(CGRect)uiLabelRect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}

- (CGSize)intrinsicContentSize {
    CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
    intrinsicSuperViewContentSize.height += topInset + bottomInset;
    intrinsicSuperViewContentSize.width += leftInset + rightInset;
    return intrinsicSuperViewContentSize;
}

- (void)setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
    topInset = edgeInsets.top;
    leftInset = edgeInsets.left;
    rightInset = edgeInsets.right;
    bottomInset = edgeInsets.bottom;
    [self invalidateIntrinsicContentSize] ;
}

- (void)setBlockText:(NSString*)text {
    NSInteger lineSpacing;
    NSString *trimmedString = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    // 处理一行的情况
    if ([trimmedString rangeOfString:@"\n"].location == NSNotFound) {
        lineSpacing = 0;
    } else {
        lineSpacing = 7;
    }
    
    [self setBlockText:trimmedString fontSize:15 lineSpacing:lineSpacing];
}

- (void)setBlockText:(NSString*)text fontSize:(NSInteger)fontSize lineSpacing:(NSInteger)lineSpacing {
    [self setFont:[UIFont systemFontOfSize:fontSize]];
    
    NSMutableAttributedString* attrString = [[NSMutableAttributedString  alloc] initWithString:text];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    
    [style setLineSpacing:lineSpacing];
    
    // 是的写死了,不要在意哈哈哈
    style.firstLineHeadIndent = 20.0;
    style.headIndent = 20.0;
    style.tailIndent = -20.0;
    
    [attrString addAttribute:NSParagraphStyleAttributeName
                       value:style
                       range:NSMakeRange(0, text.length)];
    
    self.attributedText = attrString;
}

@end
// ViewController.m

#import "ViewController.h"
#import "CodeBlockLabel.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加 UIScrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addSubview:scrollView];
    
    // 这里添加更多的文本,就能看到滚动条了
    NSString *text = @"藏在众多孤星之中\n还是找得到你";
    CodeBlockLabel *codeBlock = [[CodeBlockLabel alloc] init];
    [codeBlock setBlockText:text];
    
    // 这个 spongeBob 去掉会有 bug
    UILabel *spongeBob = [[UILabel alloc] init];
    spongeBob.numberOfLines = 0;
    spongeBob.translatesAutoresizingMaskIntoConstraints = NO;
    
    [scrollView addSubview:spongeBob];
    [scrollView addSubview:codeBlock];
    
    NSDictionary *views = @{
                            @"scrollView": scrollView,
                            @"codeBlock": codeBlock,
                            @"spongeBob": spongeBob,
                            };
    
    // 添加约束
    NSArray *constraints = nil;
    
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[codeBlock]-10-|" options:0 metrics:nil views:views];
    
    [scrollView addConstraints:constraints];
    
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[spongeBob(scrollView)]|" options:0 metrics:nil views:views];
    [scrollView addConstraints:constraints];
    
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-15-[codeBlock]-15-[spongeBob]-5-|" options:0 metrics:nil views:views];
    
    [scrollView addConstraints:constraints];
    
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[scrollView]|" options:0 metrics:nil views:views];
    
    [self.view addConstraints:constraints];
    
    constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-30-[scrollView]-44-|" options:0 metrics:nil views:views];
    
    [self.view addConstraints:constraints];
}

@end

这就是全部了,上面还添加了一个 UIScrollView,这样就算文本太长,你也能滑到下面去看了,你的更好的办法吗?有的话一定要告诉我!

参考文章

UILabel + UIScrollView + Auto Layout

上一篇 下一篇

猜你喜欢

热点阅读