美文网首页swift开发技术Swift
Swift 富文本 设置行间距 字符间距

Swift 富文本 设置行间距 字符间距

作者: Aliv丶Zz | 来源:发表于2020-12-08 14:07 被阅读0次
    • 给UILabel、UITextView等文本设置行间距、字间距等,通常都是通过设置其attributedText属性进行实现

    1. 给String进行扩展

    extension String{
    /// 富文本设置 字体大小 行间距 字间距
        func attributedString(font: UIFont, textColor: UIColor, lineSpaceing: CGFloat, wordSpaceing: CGFloat) -> NSAttributedString {
            
            let style = NSMutableParagraphStyle()
            style.lineSpacing = lineSpaceing
            let attributes = [
                    NSAttributedString.Key.font             : font,
                    NSAttributedString.Key.foregroundColor  : textColor,
                    NSAttributedString.Key.paragraphStyle   : style,
                    NSAttributedString.Key.kern             : wordSpaceing]
                
                as [NSAttributedString.Key : Any]
            let attrStr = NSMutableAttributedString.init(string: self, attributes: attributes)
            
            // 设置某一范围样式
            // attrStr.addAttribute(<#T##name: NSAttributedString.Key##NSAttributedString.Key#>, value: <#T##Any#>, range: <#T##NSRange#>)
            return attrStr
        }
    }
    
    关键字.png
    注意 段落样式中可已设置的属性很多,常用的有:

    // style.lineSpacing - 行间距
    // style.lineBreakMode - 分割样式
    // style.alignment - 对齐方式
    // style.firstLineHeadIndent - 首行缩进

    等等

    2. 使用方式

    
    let tempStr = "哈哈哈哈哈哈哈哈哈哈"
    let label = UILabel()
    //给 tempStr 设置 样式
    label.attributedText = tempStr.attributedString(font: .systemFont(ofSize: 14), textColor: .red, lineSpaceing: 10, wordSpaceing: 1.5)
    
    

    3. 其他: 给某一区间字符设置样式

    • 通过这种方式可以设置一个字符串中多种字体颜色、字体大小等
      addAttribute(NSAttributedString.Key, value: Any, range: NSRange)
     //给attrStr 前十个字符设置为红色
     attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 10))
    
    

    相关文章

      网友评论

        本文标题:Swift 富文本 设置行间距 字符间距

        本文链接:https://www.haomeiwen.com/subject/tkwfgktx.html