用label显示文章的时候要实现首行缩进的问题,但是ios10 ios 9 ios 8这三个版本其中10 和 8 用\t 可以正常显示 但是 9 \t 这个占位符太不明显,所以换一种方法来进行首行缩进。
主要知识点:1.NSMutableParagraphStyle
2.NSMutableAttributedString
上代码
/**
设置首行缩进
- parameter str: 要修改的文字
- returns: 修改后的文字
*/
func firstLineHeadIndent(str:String) -> NSMutableAttributedString
{
let mutableString = NSMutableAttributedString.init(string: str)
let style = NSMutableParagraphStyle()
style.alignment = .Left
//设置首行边距 像素 这边要根据字体大小来设置
style.firstLineHeadIndent = 28
let attr:[String:AnyObject] = [
NSFontAttributeName:UIFont.systemFontOfSize(13),
NSForegroundColorAttributeName:PublicAttributePool().textColorCray,
NSParagraphStyleAttributeName:style
]
mutableString.addAttributes(attr, range: NSRange.init(location: 0, length: str.characters.count - 1))
return mutableString
}
此外附上官方文档的提醒:
IMPORTANT
A paragraph style object should not be mutated after adding it to an attributed string; doing so can cause your program to crash.
段落样式属性在添加进属性字符串之后不要再改变其设置,否则会导致程序崩溃。