NSAttributedString 的使用

字体

// UIFont, default Helvetica(Neue) 12
// 设置字体,默认是  Helvetica(Neue) 12
public let NSFontAttributeName: String 
let attributeString = NSMutableAttributedString(string: "Hello world!")
// let font = UIFont(name: "ArialMT", size: 25)  这样设置就可以使用对应的字体集。
// 当系统中不存在的时候,可能会报错。
let font = UIFont.systemFont(ofSize: 25)

// 这个 range 会决定 font 影响的字符范围
//(最能体现个性化的地方)
let range = NSRange(location: 0, length: attributeString.length)
attributeString.addAttribute(NSFontAttributeName, value: font, range:  range)

// 设置 label 的属性文本 
label.attributedText = attributeString

将 attributeString 添加到 Label 或者 TextView 的 attributedText 的上面就可以显示出来。

Snip20160927_3.png

段落样式的设置


// NSParagraphStyle, default defaultParagraphStyle
// 段落样式
public let NSParagraphStyleAttributeName: String 

NSParagraphStyleAttributeName key 对应的 Value 是 NSMutableParagraphStyle与NSParagraphStyle
相关参考博客:
NSMutableParagraphStyle与NSParagraphStyle的使用

NSParagraphStyle 主要是用来获取 default 的段落样式(NSParagraphStyle.default 来获取默认段落样式),不具有可操作性,CoreText 开发中主要使用的是 NSMutableParagraphStyle

// 段落样式实例
open class NSMutableParagraphStyle : NSParagraphStyle {
    open var lineSpacing: CGFloat                    // 行间距
    open var paragraphSpacing: CGFloat               // 段间隙
    open var alignment: NSTextAlignment              // 文本排列 (对齐方式)
    open var firstLineHeadIndent: CGFloat            // 首行缩进
    open var headIndent: CGFloat                     // 整体缩进(首行除外)
    open var tailIndent: CGFloat
    open var lineBreakMode: NSLineBreakMode          // 换行模式
    open var minimumLineHeight: CGFloat              // 最小行高 
    open var maximumLineHeight: CGFloat              // 最大行高
    open var baseWritingDirection: NSWritingDirection    // 文本的书写方向(方向有三个,从左到右,从右到做,从上到下)
    open var lineHeightMultiple: CGFloat
    open var paragraphSpacingBefore: CGFloat         //段首行空白空
    open var hyphenationFactor: Float                // 连字属性 在iOS,唯一支持的值分别为0和1 
    @available(iOS 7.0, *)
    open var tabStops: [NSTextTab]!
    @available(iOS 7.0, *)
    open var defaultTabInterval: CGFloat
    @available(iOS 9.0, *)
    open var allowsDefaultTighteningForTruncation: Bool
    @available(iOS 9.0, *)
    open func addTabStop(_ anObject: NSTextTab)
    @available(iOS 9.0, *)
    open func removeTabStop(_ anObject: NSTextTab)
    @available(iOS 9.0, *)
    open func setParagraphStyle(_ obj: NSParagraphStyle)
}
没有设置的时候
// 加载字符串 并 创建属性文本
let strPath = Bundle.main.path(forResource: "CoreText.txt", ofType: nil)
var str: String = ""
// 这里写的稍稍有点累赘
do {
    if let tempPath = strPath {
    try str = String(contentsOf: URL(fileURLWithPath: tempPath))
    } else {
         fatalError("文件没有找到")
    }
} catch {
     fatalError("文件价值失败")
}
let attributeString = NSMutableAttributedString(string: str)
        
// 设置字符属性  设置段落样式
let style = NSMutableParagraphStyle()
style.lineSpacing = 3               // 设置行间距
style.firstLineHeadIndent = 20.0    // 设置首行缩进
style.paragraphSpacing = 3          // 设置段落之间的间距
        
attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: range)
调整后的

相对来说已经美观很多了。

文字颜色和背景颜色的处理

// UIColor, default blackColor
// 设置文字颜色, 默认为黑色
public let NSForegroundColorAttributeName: String 

// UIColor, default nil: no background
// 设置文字的背景颜色,默认是没有颜色的
public let NSBackgroundColorAttributeName: String 

// 设置字体颜色
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)
        
// 设置字体背景颜色
attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.blue, range: range)
Snip20160927_6.png

连字符

连体字符是指某些连在一起的字符,它们采用 单个的图元符号。0 表示没有连体字符。1 表示使用默认的连体字符。2表示使用所有连体符号。默认值为 1(注意,iOS 不支持值为 2)。

(不是使用了 1 后 所有的字符都会连起来)


// NSNumber containing integer, default 1: default ligatures, 0: no ligatures
// 设置连体字(只有 0 和 1 可以设置,1 表示连体字,0 表示非连体字)
public let NSLigatureAttributeName: String 

设置字符间距

值为 0 表示不使用字母紧排。默认值为0。 正数,间距增加,负数,间距减小。

// NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.
// 设置文字间的间距(字符之间的间距)(正数,间距增加,负数,间距减小)
public let NSKernAttributeName: String 

设置删除线

删除线的样式可以参考 NSUnderlineStyle进行设置

 // NSNumber containing integer, default 0: no strikethrough
 // 设置文字删除线的样式
public let NSStrikethroughStyleAttributeName: String

// UIColor, default nil: same as foreground color
// 设置文字删除线的颜色
public let NSStrikethroughColorAttributeName: String 

下划线的设置

// NSNumber containing integer, default 0: no underline
// 设置下划线的样式 
public let NSUnderlineStyleAttributeName: String 

// UIColor, default nil: same as foreground color
// 设置下划线颜色 , 默认和文字颜色是一样的
public let NSUnderlineColorAttributeName: String 

// 下划线的样式
public enum NSUnderlineStyle : Int {
    case styleNone
    case styleSingle

    @available(iOS 7.0, *)
    case styleThick
    @available(iOS 7.0, *)
    case styleDouble

    @available(iOS 7.0, *)
    public static var patternSolid: NSUnderlineStyle { get }

    @available(iOS 7.0, *)
    case patternDot

    @available(iOS 7.0, *)
    case patternDash

    @available(iOS 7.0, *)
    case patternDashDot

    @available(iOS 7.0, *)
    case patternDashDotDot

    @available(iOS 7.0, *)
    case byWord
}

// 设置下划线  (写 NSUnderlineStyle.styleSingle 编译不通过,但是写 1 编译通过,效果是等效的。 )
attributeString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: range)

attributeString.addAttribute(NSUnderlineColorAttributeName, value: UIColor.green, range: range)
Snip20160928_7.png

设置文字的描边

NSStrokeColorAttributeName 和 NSStrokeWidthAttributeName 配合使用才会有效果。单独使用时不会有效果的。
使用两个属性,会让文字产生镂空的效果。

属性不指定(默认),则等同于 NSForegroundColorAttributeName。否则,指定为删除线或下划线颜色。

设置描边效果后 Width > 0 NSForegroundColorAttributeName 字符属性的设置就会失效。

// UIColor, default nil: same as foreground color
// 设置文字绘制颜色(和 foreground color 一样)
public let NSStrokeColorAttributeName: 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)
// 设置文字笔画宽度的百分比, 相对于字体size 的百分比.
// 正数只改变描边宽度。负数同时改变文字的描边和填充宽度。例如,对于常见的空心字,这个值通常为3.0。(空心文字)
public let NSStrokeWidthAttributeName: String 
let str: String = "Hello world!"
let attributeString = NSMutableAttributedString(string: str)

//  设置字符属性
let font = UIFont.systemFont(ofSize: 35)

// 这个 range 会决定 font 影响的字符范围
let range = NSRange(location: 0, length: attributeString.length)
attributeString.addAttribute(NSFontAttributeName, value: font, range:  range)

attributeString.addAttribute(NSStrokeColorAttributeName, value: UIColor.green, range: range)

//  value 的值为 3 。 这个时候文字是镂空的
attributeString.addAttribute(NSStrokeWidthAttributeName, value: 3, range: range)
镂空效果
//  value 的值为 -3
attributeString.addAttribute(NSStrokeWidthAttributeName, value: -3, range: range)
Snip20160928_9.png
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)

描边后,文字的填充颜色是由文字的颜色决定的。


Snip20160928_10.png

文字阴影

文字阴影对应的是 NSShadow 对象。默认情况下是 nil
(我发现单独使用是不会有效果的)

// NSShadow, default nil: no shadow
// 设置文字阴影
public let NSShadowAttributeName: String 

图版印刷效果

// NSString, default nil: no text effect
// 设置文本效果 目前只有图版印刷效果可用
public let NSTextEffectAttributeName: String 

图文混排列

// NSTextAttachment, default nil
// 设置文本附件(图文混排相关)
public let NSAttachmentAttributeName: String 

网络连接的处理

// NSURL (preferred) or NSString
// 设置网络连接(设置链接,点击后用浏览器打开)
public let NSLinkAttributeName: String 

// NSNumber containing floating point value, in points; offset from baseline, default 0
// 设置文字基准线偏移量 ( 正值向上偏移,负值向下偏移)
public let NSBaselineOffsetAttributeName: String 


// NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew
// 设置文字的斜体效果(正值向左偏,负值向右偏)
public let NSObliquenessAttributeName: String 

// NSNumber containing floating point value; log of expansion factor to be applied to glyphs, default 0: no expansion
// 设置文字扩充 (正数向左右拉伸,负数 向中间缩小)
public let NSExpansionAttributeName: 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,
// 设置文字的书写方向(从左到右,从右到左)
public let NSWritingDirectionAttributeName: String 


字符排列

// An NSNumber containing an integer value.  0 means horizontal text.  1 indicates vertical text.  
// If not specified, it could follow higher-level vertical orientation settings.  Currently on iOS, it's always horizontal.  
// The behavior for any other value is undefined.
// 设置文字的垂直样式(测试只对中文标点起作用,0 横排列,1 竖直排列) iOS 一般使用 0 
public let NSVerticalGlyphFormAttributeName: String 

// This defines currently supported values for NSUnderlineStyleAttributeName and NSStrikethroughStyleAttributeName. 
// NSUnderlineStyle*, NSUnderlinePattern*, and NSUnderlineByWord are or'ed together to produce an underline style.



Attribute values

// NSWritingDirectionFormatType values used by NSWritingDirectionAttributeName. It is or'ed with either NSWritingDirectionLeftToRight or NSWritingDirectionRightToLeft. Can specify the formatting controls defined by Unicode Bidirectional Algorithm.
@available(iOS 9.0, *)
public enum NSWritingDirectionFormatType : Int {

    case embedding

    case override
}

// NSTextEffectAttributeName values
@available(iOS 7.0, *)
public let NSTextEffectLetterpressStyle: String

Attribute fixing


/************************ Attribute fixing ************************/
extension NSMutableAttributedString {

    // This method fixes attribute inconsistencies inside range.  It ensures NSFontAttributeName covers the characters, NSParagraphStyleAttributeName is only changing at paragraph boundaries, and NSTextAttachmentAttributeName is assigned to NSAttachmentCharacter.  NSTextStorage automatically invokes this method via -ensureAttributesAreFixedInRange:.
    @available(iOS 7.0, *)
    open func fixAttributes(in range: NSRange)
}


// Supported document types for the NSDocumentTypeDocumentAttribute key in the document attributes dictionary.
/************************ Document formats ************************/
@available(iOS 7.0, *)
public let NSPlainTextDocumentType: String
@available(iOS 7.0, *)
public let NSRTFTextDocumentType: String
@available(iOS 7.0, *)
public let NSRTFDTextDocumentType: String
@available(iOS 7.0, *)
public let NSHTMLTextDocumentType: String

// Keys for NSLayoutOrientationSectionsAttribute.
@available(iOS 7.0, *)
public let NSTextLayoutSectionOrientation: String // NSNumber containing NSTextLayoutOrientation value. default: NSTextLayoutOrientationHorizontal
@available(iOS 7.0, *)
public let NSTextLayoutSectionRange: String // NSValue containing NSRange representing a character range. default: a range covering the whole document

// Keys for options and document attributes dictionaries.  They are in and out document properties used by both read/write methods.

@available(iOS 7.0, *)
public let NSDocumentTypeDocumentAttribute: String // @"DocumentType", one of the document types declared above.  For reader methods, this key in options can specify the document type for interpreting the contents.  Upon return, the document attributes can contain this key for indicating the actual format used to read the contents.  For write methods, this key specifies the format for generating the data.

// NSPlainTextDocumentType document attributes
@available(iOS 7.0, *)
public let NSCharacterEncodingDocumentAttribute: String // @"CharacterEncoding", NSNumber containing integer specifying NSStringEncoding for the file; default for plain text is the default encoding.  This key in options can specify the string encoding for reading the data.  Upon return, the document attributes can contain the actual encoding used.  For writing methods, this value is used for generating the plain text data.
@available(iOS 7.0, *)
public let NSDefaultAttributesDocumentAttribute: String // @"DefaultAttributes", NSDictionary containing attributes to be applied to plain files.  Used by reader methods.  This key in options can specify the default attributes applied to the entire document contents.  The document attributes can contain this key indicating the actual attributes used.

// NSRTFTextDocumentType and NSRTFDTextDocumentType document attributes
// Document dimension
// They are document attributes used by read/write methods.
@available(iOS 7.0, *)
public let NSPaperSizeDocumentAttribute: String // @"PaperSize", NSValue containing CGSize (in points)
@available(iOS 7.0, *)
public let NSPaperMarginDocumentAttribute: String // @"PaperMargin", NSValue containing UIEdgeInsets

@available(iOS 7.0, *)
public let NSViewSizeDocumentAttribute: String // @"ViewSize", NSValue containing CGSize (in points)
@available(iOS 7.0, *)
public let NSViewZoomDocumentAttribute: String // @"ViewZoom", NSNumber containing floating point value (100 == 100% zoom)
@available(iOS 7.0, *)
public let NSViewModeDocumentAttribute: String // @"ViewMode", NSNumber containing integer; 0 = normal; 1 = page layout

// Document settings
// They are document attributes used by read/write methods.
@available(iOS 7.0, *)
public let NSReadOnlyDocumentAttribute: String // @"ReadOnly", NSNumber containing integer; if missing, or 0 or negative, not readonly; 1 or more, readonly. Note that this has nothing to do with the file system protection on the file, but instead, on how the file should be displayed to the user
@available(iOS 7.0, *)
public let NSBackgroundColorDocumentAttribute: String // @"BackgroundColor", UIColor, representing the document-wide page background color
@available(iOS 7.0, *)
public let NSHyphenationFactorDocumentAttribute: String // @"HyphenationFactor", NSNumber containing floating point value (0=off, 1=full hyphenation)
@available(iOS 7.0, *)
public let NSDefaultTabIntervalDocumentAttribute: String // @"DefaultTabInterval", NSNumber containing floating point value, representing the document-wide default tab stop interval, in points
@available(iOS 7.0, *)
public let NSTextLayoutSectionsAttribute: String // NSArray of dictionaries.  Each dictionary describing a layout orientation section.  The dictionary can have two attributes: NSTextLayoutSectionOrientation and NSTextLayoutSectionRange.  When there is a gap between sections, it's assumed to have NSTextLayoutOrientationHorizontal.

extension NSAttributedString {

    // Methods initializing the receiver contents with an external document data.  options specify document attributes for interpreting the document contents.  NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute, and NSDefaultAttributesDocumentAttribute are supported options key.  When they are not specified, these methods will examine the data and do their best to detect the appropriate attributes.  If dict is non-NULL, it will return a dictionary with various document-wide attributes accessible via NS...DocumentAttribute keys.
    @available(iOS 9.0, *)
    public init(url: URL, options: [String : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws

    @available(iOS 7.0, *)
    public init(data: Data, options: [String : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws

    
    // Generates an NSData object for the receiver contents in range.  It requires a document attributes dict specifying at least the NSDocumentTypeDocumentAttribute to determine the format to be written.
    @available(iOS 7.0, *)
    open func data(from range: NSRange, documentAttributes dict: [String : Any] = [:]) throws -> Data

    
    // Returns an NSFileWrapper object for the receiver contents in range.  It requires a document attributes dict specifying at least the NSDocumentTypeDocumentAttribute to determine the format to be written.  The method returns a directory file wrapper for those document types represented by a file package such as NSRTFDTextDocumentType; otherwise, it returns a regular-file file wrapper.
    @available(iOS 7.0, *)
    open func fileWrapper(from range: NSRange, documentAttributes dict: [String : Any] = [:]) throws -> FileWrapper
}

extension NSMutableAttributedString {

    // Methods replacing the receiver contents with an external document data.  options specify document attributes for interpreting the document contents.  NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute, and NSDefaultAttributesDocumentAttribute are supported options key.  When they are not specified, these methods will examine the data and do their best to detect the appropriate attributes.  If dict is non-NULL, it will return a dictionary with various document-wide attributes accessible via NS...DocumentAttribute keys.
    @available(iOS 9.0, *)
    open func read(from url: URL, options opts: [String : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws

    @available(iOS 7.0, *)
    open func read(from data: Data, options opts: [String : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws
}

/************ Misc methods(混合方法) ****************/
extension NSAttributedString {

    // Returns YES if the receiver contains a property configured (NSAttachmentAttributeName with NSAttachmentCharacter) in range
    @available(iOS 9.0, *)
    open func containsAttachments(in range: NSRange) -> Bool
}


/************* Deprecated 废弃(不建议使用)*****************/
@available(iOS, introduced: 7.0, deprecated: 9.0, message: "Use NSWritingDirectionFormatType instead")
public enum NSTextWritingDirection : Int {

    
    case embedding

    case override
}

extension NSAttributedString {

    @available(iOS, introduced: 7.0, deprecated: 9.0, message: "Use -initWithURL:options:documentAttributes:error: instead")
    public init(fileURL url: URL, options: [AnyHashable : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws
}

extension NSMutableAttributedString {

    @available(iOS, introduced: 7.0, deprecated: 9.0, message: "Use -readFromURL:options:documentAttributes:error: instead")
    open func read(fromFileURL url: URL, options opts: [AnyHashable : Any] = [:], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>?) throws
}

http://www.itnose.net/detail/6177538.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • 与NSString类似,在iOS中AttributedString也分为NSAttributedString和 N...
    钱十六阅读 726评论 0 0
  • 转载:http://blog.csdn.net/u010330109/article/details/518821...
    F麦子阅读 4,062评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • { 24、Sqlite数据库 1、存储大数据量,增删改查,常见管理系统:Oracle、MSSQLServer、DB...
    CYC666阅读 895评论 0 1
  • 第十五节。主力盘口语言 本节大家要了解一下就好。就当听了个传说。但这却是真实发生的事情。庄家们在许多时候为了不被查...
    精彩飞神阅读 361评论 0 2