字體
// 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) 這樣設置就可以使用對應的字體集娃闲。
// 當系統(tǒng)中不存在的時候,可能會報錯匾浪。
let font = UIFont.systemFont(ofSize: 25)
// 這個 range 會決定 font 影響的字符范圍
//(最能體現(xiàn)個性化的地方)
let range = NSRange(location: 0, length: attributeString.length)
attributeString.addAttribute(NSFontAttributeName, value: font, range: range)
// 設置 label 的屬性文本
label.attributedText = attributeString
將 attributeString 添加到 Label 或者 TextView 的 attributedText 的上面就可以顯示出來皇帮。
段落樣式的設置
// NSParagraphStyle, default defaultParagraphStyle
// 段落樣式
public let NSParagraphStyleAttributeName: String
NSParagraphStyleAttributeName key 對應的 Value 是 NSMutableParagraphStyle與NSParagraphStyle
相關參考博客:
NSMutableParagraphStyle與NSParagraphStyle的使用
NSParagraphStyle 主要是用來獲取 default 的段落樣式(NSParagraphStyle.default 來獲取默認段落樣式),不具有可操作性蛋辈,CoreText 開發(fā)中主要使用的是 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)
}
// 加載字符串 并 創(chuàng)建屬性文本
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)
相對來說已經(jīng)美觀很多了。
文字顏色和背景顏色的處理
// 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)
連字符
連體字符是指某些連在一起的字符,它們采用 單個的圖元符號苗胀。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健田。 正數(shù)虹脯,間距增加淑仆,負數(shù)漆诽,間距減小。
// NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.
// 設置文字間的間距(字符之間的間距)(正數(shù)扮休,間距增加迎卤,負數(shù),間距減戌枳埂)
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)
設置文字的描邊
NSStrokeColorAttributeName 和 NSStrokeWidthAttributeName 配合使用才會有效果樟凄。單獨使用時不會有效果的。
使用兩個屬性兄渺,會讓文字產(chǎn)生鏤空的效果缝龄。
屬性不指定(默認),則等同于 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 的百分比.
// 正數(shù)只改變描邊寬度炼绘。負數(shù)同時改變文字的描邊和填充寬度。例如妄田,對于常見的空心字俺亮,這個值通常為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)
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)
描邊后脚曾,文字的填充顏色是由文字的顏色決定的。
文字陰影
文字陰影對應的是 NSShadow 對象萨醒。默認情況下是 nil
(我發(fā)現(xiàn)單獨使用是不會有效果的)
// 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
網(wǎng)絡連接的處理
// NSURL (preferred) or NSString
// 設置網(wǎng)絡連接(設置鏈接斟珊,點擊后用瀏覽器打開)
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
// 設置文字擴充 (正數(shù)向左右拉伸囤踩,負數(shù) 向中間縮小)
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
}