Swift4之NSAttributedString的使用

Swift富文本使用

NSAttributeString的优点

1.多样式的显示富文本信息。

2.可用于图文混排,借助NSTextAttachment。

3.一条语句代码(属性字典)可以设置多个属性。

swift3使用NSAtrributedString

let attributedString = NSAttributedString(string: "富文本测试", attributes: [ NSBackgroundColorAttributeName : UIColor.red,NSForegroundColorAttributeName : UIColor.green])


Swift4版本

let attributeString = NSAttributedString(string: "富文本测试", attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 13.5)])


//注意:Swift使用NSAttributedStringKey去掉相关属性。所以在使用的使用需要有点小变化,主要属性关键字还是差不多。

文本属性关键字如下:

swift3版本示例

//设置字体
let NSFontAttributeName: String // UIFont, default Helvetica(Neue) 12
//设置段落样式
let NSParagraphStyleAttributeName: String // NSParagraphStyle, default defaultParagraphStyle
//设置前景色(字体色),如果设置字体线条色,则无效,字体内部为字体背景色
let NSForegroundColorAttributeName: String // UIColor, default blackColor

 

Swift4使用NSAttributedStringKey.点关键字示例

 

extension NSAttributedStringKey {

    
    /************************ Attributes ************************/
    @available(iOS 6.0, *)
    public static let font: NSAttributedStringKey

    @available(iOS 6.0, *)
    public static let paragraphStyle: NSAttributedStringKey // NSParagraphStyle, default defaultParagraphStyle

    @available(iOS 6.0, *)
    public static let foregroundColor: NSAttributedStringKey // UIColor, default blackColor

 

 

 

注意:如果设置字体线条色,且描边宽度为正值(中空形式)则无效,显示为字体背景色

这里虽然我设置的字体色为绿色,但是设置了描边色,且宽度为正值,并没有起效果,

同样的,如果描边宽度设置为负值(-3),即正常显示了。

 

//字体背景色,与控件背景色不同
public let NSBackgroundColorAttributeName: String // UIColor, default nil: no background

 

//连字符,反正我不懂干嘛的
public let NSLigatureAttributeName: String // NSNumber containing integer, default 1: default ligatures, 0: no ligatures
//字间距,正值加宽,负值变窄
public let NSKernAttributeName: String // NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.
//删除线 ,值可以使用整数(0-7:单线,值越大,线越粗,7-15:双线,同理)或者枚举(参考下面枚举定义)
public let NSStrikethroughStyleAttributeName: String // NSNumber containing integer, default 0: no strikethrough
//下划线, 值同删除线
public let NSUnderlineStyleAttributeName: String // NSNumber containing integer, default 0: no underline
//字体边框颜色,设置此颜色
public let NSStrokeColorAttributeName: String // UIColor, default nil: same as foreground color
//字体变框宽度,如果设置了边框色,需要设置这个颜色,否则看不到,【重点:值可以为正值(中空形式,字体色为字体背景色)和负值(填充形式:设置字体颜色可以显示)】
public let NSStrokeWidthAttributeName: String // NSNumber containing floating point value, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)
//字体阴影,
public let NSShadowAttributeName: String // NSShadow, default nil: no shadow
//文本特殊效果,只有图文排版印刷使用
public let NSTextEffectAttributeName: String // NSString, default nil: no text effect
//图文混排
public let NSAttachmentAttributeName: String // NSTextAttachment, default nil

public let NSLinkAttributeName: String // NSURL (preferred) or NSString
//基线偏移,正值向上,负值向下
public let NSBaselineOffsetAttributeName: String // NSNumber containing floating point value, in points; offset from baseline, default 0
//底线的颜色
public let NSUnderlineColorAttributeName: String // UIColor, default nil: same as foreground color
//删除线颜色
public let NSStrikethroughColorAttributeName: String // UIColor, default nil: same as foreground color
//字体倾斜度,正值左倾,负值右倾
public let NSObliquenessAttributeName: String // NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew
//文本横线拉伸,正值拉伸,负值压缩
public let NSExpansionAttributeName: String // NSNumber containing floating point value;

 

//字体书写方向,从左到右,与从右到左,值参考下面
public let NSWritingDirectionAttributeName: String // NSArray of NSNumbers representing the nested levels of writing direction overrides as defined by Unicode LRE, RLE, LRO, and RLO characters.

字体书写方向值:

 

The control characters can be obtained by masking NSWritingDirection and NSWritingDirectionFormatType values.  
 LRE: NSWritingDirectionLeftToRight|NSWritingDirectionEmbedding, 
 RLE: NSWritingDirectionRightToLeft|NSWritingDirectionEmbedding, 
 LRO: NSWritingDirectionLeftToRight|NSWritingDirectionOverride, 
 RLO: NSWritingDirectionRightToLeft|NSWritingDirectionOverride,
//文字横竖排版 值为0或1,0横排,1竖排,目前ios只支持横排。
public let NSVerticalGlyphFormAttributeName: String

 

如何实现多种复合文本组合

     1.可以使用设置range

      2.通过NSAttributedMutableString 的append方法组合
具体使用参考:OC[传送门] 传送门2
 

 

使用富文本实现简单图文排版

可以通过NSTextAttachment 对象初始化NSAttributedString,从而将图片展示在文本中,照片加载在NSTextAttachment中。

注意,如果使用NSTextAttachment加载照片的时候,没有设置对象的bounds,就会以原大小显示,就可能会被遮挡。

为了实现图片的缩放完全显示可通过继承自定义NSTextAttachment类,重写设置bounds的方法。

示例代码:

//适应NSAttributeString图文排版
//图片自适应
class TextAttachment: NSTextAttachment {
    
    override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
        let attachmentWidth = lineFrag.width - (textContainer?.lineFragmentPadding)! * 2
        return scaleImageSizeToWidth(width: attachmentWidth)
    }
    
    func scaleImageSizeToWidth(width:CGFloat) -> CGRect {
        let factor = CGFloat(width / (self.image?.size.width)!)
        return CGRect.init(x: 0, y: 0, width: (image?.size.width)!*factor, height: (image?.size.height)!*factor)
    }
}
            let imageAttachment =  TextAttachment()
            imageAttachment.image = editImage as! UIImage
            let attributedText = self.textView.attributedText
            let newAttribtedText = NSMutableAttributedString(attributedString: attributedText!)
            newAttribtedText.append(NSAttributedString.init(attachment: imageAttachment)) //将图片加上去,以NSAttributedString方式
            self.textView.attributedText = newAttribtedText

加载简单html

有时候后台为了统一控制,可能会返回控制html,如果是比较简单的,我们可以不用WebKit处理,直接利用Label或者textView的富文本属性都可以加载。

//html 片段
let htmlString =
        """
        <html>
        <bady>
        <p style="color:red;font-size:15">
        这是一个段落文字
        </p>
            <p>
        这是另外一个段落
        </p>
        <bady>
        </html>
        """
//使用富文本加载
let txtAttrStr = try! NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) //文档读取属性为html
//添加到label上
label.attributedText = txtAttrStr;

不过注意的是本地资源图片无法加载处理,不知道是不是我的路径没有对,但是加载网路图片却可以。

//如 加载一张本地的svg图片,在uilabel中没有效果,
//但是通过WKWebView加载却可以。  而加载网络图片也是可以的。
<img src="./Dollar.svg" height="100" width="100" />

 

 

 

 

 

 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值