NSString *text = @"守夜人誓言:「長夜將至,我從今開始守望,至死方休。我將不娶妻、不封地、不生子。我將不戴寶冠,不爭榮寵。我將盡忠職守,生死於斯。我是黑暗中的利劍,長城上的守衛。我是抵御寒冷的烈焰,破曉時分的光線,喚醒眠者的號角,守護王國的堅盾。我將生命與榮耀獻給守夜人,今夜如此,夜夜皆然。」";
//設置文本屬性
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc]init];
//設置行間距
[paraStyle setLineSpacing:5];
[paraStyle setLineBreakMode:NSLineBreakByWordWrapping];
//字體大小
UIFont *textFont = [UIFont systemFontOfSize:15];
//字體顏色
UIColor *textColor = [UIColor lightGrayColor];
NSDictionary *textDic = @{NSFontAttributeName : textFont,NSForegroundColorAttributeName : textColor,NSParagraphStyleAttributeName : paraStyle};
//富文本
NSAttributedString *attrText = [[NSAttributedString alloc]initWithString:text attributes:textDic];
//計算文本的size
CGSize textSize = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width *0.5, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:textDic context:nil].size;
UILabel *textLabel = [[UILabel alloc]init];
textLabel.attributedText = attrText;
textLabel.numberOfLines = 0;
[self.view addSubview:textLabel];
//布局
[textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.mas_equalTo(self.view);
make.width.mas_equalTo(ceil(textSize.width));//
make.height.mas_equalTo(ceil(textSize.height));
}];
//設置虛線邊框
CAShapeLayer *borderLayer = [CAShapeLayer layer];
borderLayer.bounds = CGRectMake(0, 0, textSize.width + 10, textSize.height + 10);
//中心點位置
borderLayer.position = CGPointMake(textSize.width *0.5, textSize.height *0.5);
borderLayer.path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, textSize.width + 10, textSize.height + 10)].CGPath;
//邊框的寬度
borderLayer.lineWidth = 3;
//邊框虛線線段的寬度
borderLayer.lineDashPattern = @[@5,@5];
borderLayer.fillColor = [UIColor clearColor].CGColor;
borderLayer.strokeColor = [UIColor purpleColor].CGColor;
[textLabel.layer addSublayer:borderLayer];
效果如下: