字体
// 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 的上面就可以显示出来。
![](https://img.haomeiwen.com/i446092/2281a78ff2ddd7eb.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)
}
![](https://img.haomeiwen.com/i446092/70b8f721e81433a3.png)
// 加载字符串 并 创建属性文本
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)
![](https://img.haomeiwen.com/i446092/aef3f49fc0a6d9d9.png)
相对来说已经美观很多了。
文字颜色和背景颜色的处理
// 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)
![](https://img.haomeiwen.com/i446092/fc50d49579de2ed0.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)
![](https://img.haomeiwen.com/i446092/3c73864565b9bf78.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)
![](https://img.haomeiwen.com/i446092/9ab827fb97068988.png)
// value 的值为 -3
attributeString.addAttribute(NSStrokeWidthAttributeName, value: -3, range: range)
![](https://img.haomeiwen.com/i446092/5d5285c3149dd64a.png)
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)
描边后,文字的填充颜色是由文字的颜色决定的。
![](https://img.haomeiwen.com/i446092/fcfa999b2604d908.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
}
网友评论