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 nilpublic 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)! * 2return 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! UIImagelet attributedText = self.textView.attributedTextlet 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" />
Swift4之NSAttributedString的使用相关推荐
- XCode10 swift4.2 适配遇到的坑
以下是2018年10月23日更新 经过大约一个月的时间的适配,项目正式使用XCode10(以下简称为10 or XC10)大部分库都升级为Swift4.2(以下简称为 4.2 or S4.2),下面是 ...
- 理解NSAttributedString
An NSAttributedString object manages character strings and associated sets of attributes (for exampl ...
- swift4 attributedText简单使用以及改变链接字体颜色
showTextView.delegate = selflet str = showTextView.text ?? ""let title = "本<隐私政策&g ...
- NSAttributedString 详解
首先导入CoreText.framework,并在需要使用的文件中导入: #import<CoreText/CoreText.h> 创建一个NSMutableAttributedStrin ...
- 关于Swift4.0 Method Swizzling(iOS的hook机制)使用
2019独角兽企业重金招聘Python工程师标准>>> 关于Method Swizzling 原理什么的有很多帖子讲述的已经很清楚这里不再赘述, 这里仅仅处理Method Swizz ...
- swift4.0-11 类和结构体
代码学习swift4.0, 类和结构体 // // main.swift // SwiftLearn11-类和结构体 // // Created by iOS on 2018/5/7. // Copy ...
- UILabel上展示不同颜色的文字(NSAttributedString)
时间 2014-03-31 21:18:28 CSDN博客原文 http://blog.csdn.net/u011439689/article/details/22693679 首先导入CoreT ...
- Swift4.1第二章 The Basics
Swift语言开发指南 基础部分 Swift是一门新的开发语言,它可以在iOS.macOS watchOS以及tvOS系统环境下进行应用的开发. Swift提供了它自己的C和Objective-C语言 ...
- ios NSAttributedString 具体解释
ios NSAttributedString 具体解释 NSAttributedString能够让我们使一个字符串显示的多样化,可是眼下到iOS 5为止,好像对它支持的不是非常好,由于显示起来不太方便 ...
最新文章
- 博士生宿舍条件太好,本科生因疫情暂住惊到结巴!网友:不然咱读个博?
- java 跨域上传_java使用webuploader实现跨域上传详解
- netflix测试能不能看_Netflix监管者测试–引入知事,准官员
- 实用程序类的OOP替代
- 刷抖音看到 Python 工程师的工资条后,我沉默了...
- 一天一个设计模式之JS实现——建造者模式
- Greenplum分区
- 基于JAVA+Servlet+JSP+MYSQL的保险管理系统
- C语言小程序:找出100以内素数
- 送书 | 《Python3爬虫实战——数据清洗、数据分析与可视化》
- win10 外接usb摄像头_win10系统外接摄像头不能用怎么办
- 一、绘制不同类别特征均值标准差直方图
- 温故而知新,19646字Java基础知识梳理
- Zxing扫描条形码后得到结果前面多了一个0的问题
- (附源码)spring boot网上购物系统 毕业设计 311236
- Expected binary or unicode string, got 3
- 如何免费创建一个自己的网站(可通过外网访问)
- java基础之import语句_繁星漫天_新浪博客
- Vue-生命周期-axios
- 腾讯云服务器linux+CentOS7.9+yum源+nginx搭建网站