todo
- [ x ] 自己改造了富文本的屬性設(shè)置
- [ ] 代碼中用到的API后續(xù)補(bǔ)上
富文本
存在文字的控件或者組建都可以設(shè)置富文本
UILabel, UIButton, UITextView 都可以設(shè)置富文本
計(jì)算文本Size
Code
import UIKit
enum TextAttributes {
/// 字體
case font(value: UIFont) // UIFont, default Helvetica(Neue) 12
/// 設(shè)置段落屬性
case paragraphStyle(value: NSParagraphStyle) // NSParagraphStyle, default defaultParagraphStyle
/// 設(shè)置前景顏色
case foregroundColor(value: UIColor) // UIColor, default blackColor
/// 設(shè)置文本背景顏色
case backgroundColor(value: UIColor) // UIColor, default nil: no background
/// 設(shè)置連體屬性鸭廷,取值為NSNumber對(duì)象(整數(shù)),1表示使用默認(rèn)的連體字符熔吗,0表示不使用,2表示使用所有連體符號(hào)(iOS不支持2)佳晶。而且并非所有的字符之間都有組合符合桅狠。如 fly ,f和l會(huì)連起來轿秧。
case ligatures(value: Int) // NSNumber containing integer, default 1: default ligatures, 0: no ligatures
/// 設(shè)置字距 中跌,負(fù)值間距變窄,正值間距變寬
case kern(value: CFloat) // NSNumber containing floating point value, in points; amount to modify default kerning. 0 means kerning is disabled.
/// 設(shè)置刪除線
case strikethroughStyle(value: NSUnderlineStyle) // NSNumber containing integer, default 0: no strikethrough
/// 設(shè)置下劃線樣式
case underlineStyle(value: NSUnderlineStyle) // NSNumber containing integer, default 0: no underline
/// 設(shè)置筆刷顏色 設(shè)置填充部分顏色 設(shè)置中間部分顏色可以使用 NSForegroundColorAttributeName 屬性來進(jìn)行
case strokeColor(value: UIColor) // UIColor, default nil: same as foreground color
/// 設(shè)置筆畫的寬度菇篡,負(fù)值填充效果漩符,正值是中空效果
case strokeWidth(value: CGFloat) // 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)
/// 設(shè)置陰影
case shadow(value: NSShadow) // NSShadow, default nil: no shadow
/// 設(shè)置文本特殊效果,目前只有一個(gè)可用效果 NSTextEffectLetterpressStyle(凸版印刷效果)
case textEffect(value: String) // NSString, default nil: no text effect NSTextEffectLetterpressStyle
/// 設(shè)置文本附件驱还,常用于文字的圖文混排
case attachment(value: NSTextAttachment) // NSTextAttachment, default nil
case linkString(value: String) // NSURL (preferred) or NSString
case linkURL(value: URL) // NSURL (preferred) or NSString
/// 設(shè)置基線偏移值 正值上偏嗜暴,負(fù)值下偏
case baselineOffset(value: CGFloat) // NSNumber containing floating point value, in points; offset from baseline, default 0
/// 設(shè)置下劃線顏色
case underlineColor(value: UIColor) // UIColor, default nil: same as foreground color
/// 設(shè)置刪除線顏色
case strikethroughColor(value: UIColor) // UIColor, default nil: same as foreground color
/// 設(shè)置字體傾斜度,正值右傾议蟆,負(fù)值左傾
case obliqueness(value: CGFloat) // NSNumber containing floating point value; skew to be applied to glyphs, default 0: no skew
/// 設(shè)置字體的橫向拉伸闷沥,取值為NSNumber (float),正值拉伸 咐容,負(fù)值壓縮
case expansion(value: CGFloat) // NSNumber containing floating point value; log of expansion factor to be applied to glyphs, default 0: no expansion
/// 設(shè)置文字的書寫方向
case writingDirection(value: [NSWritingDirection]) // 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,
/// 設(shè)置文字排版方向舆逃,0表示橫排文本,1表示豎排文本 在iOS中只支持0
case verticalGlyphForm(value: Int) // 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.
}
fileprivate func configureAttributes(attributes: [TextAttributes]?)->[String: Any]? {
guard let attributes = attributes else {
return nil
}
var temp:[String: Any] = [String: Any]()
for attribute in attributes {
switch attribute {
case let .font(value):
temp[NSFontAttributeName] = value
case let .paragraphStyle(value):
temp[NSParagraphStyleAttributeName] = value
case let .foregroundColor(value):
temp[NSForegroundColorAttributeName] = value
case let .backgroundColor(value):
temp[NSBackgroundColorAttributeName] = value
case let .ligatures(value):
temp[NSLigatureAttributeName] = value
case let .kern(value):
temp[NSKernAttributeName] = value
case let .strikethroughStyle(value):
temp[NSStrikethroughStyleAttributeName] = value
case let .underlineStyle(value):
temp[NSUnderlineStyleAttributeName] = value
case let .strokeColor(value):
temp[NSStrokeColorAttributeName] = value
case let .strokeWidth(value):
temp[NSStrokeWidthAttributeName] = value
case let .shadow(value):
temp[NSShadowAttributeName] = value
case .textEffect(_):
temp[NSTextEffectAttributeName] = NSTextEffectLetterpressStyle
case let .attachment(value):
temp[NSAttachmentAttributeName] = value
case let .linkString(value):
temp[NSLinkAttributeName] = value
case let .linkURL(value):
temp[NSLinkAttributeName] = value
case let .baselineOffset(value):
temp[NSBaselineOffsetAttributeName] = value
case let .underlineColor(value):
temp[NSUnderlineColorAttributeName] = value
case let .strikethroughColor(value):
temp[NSStrikethroughColorAttributeName] = value
case let .obliqueness(value):
temp[NSObliquenessAttributeName] = value
case let .expansion(value):
temp[NSExpansionAttributeName] = value
case let .writingDirection(value):
temp[NSWritingDirectionAttributeName] = value
case let .verticalGlyphForm(value):
temp[NSVerticalGlyphFormAttributeName] = value
}
}
return temp
}
extension String {
/// 根據(jù)文字屬性計(jì)算size
///
/// - Parameters:
/// - size: 限定size
/// - attributes: 屬性
/// - Returns: 返回新的size
fileprivate func getTextSize(string: String,size: CGSize,attributes: [TextAttributes]?)-> CGRect {
let attribute = configureAttributes(attributes: attributes)
let text = NSString(string: string)
let newSize = text.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attribute, context: nil)
return newSize
}
/// 根據(jù)文字限定的寬度來計(jì)算所占高度
///
/// - Parameters:
/// - width: 寬度
/// - attributes: 屬性
/// - Returns: 返回的高度
func getTextHeight(width: CGFloat,attributes: [TextAttributes]?) -> CGFloat {
let size = CGSize(width: width, height: 0)
let rect = getTextSize(string: self, size: size, attributes: attributes)
return rect.height
}
/// 根據(jù)文字限定的高度來計(jì)算所占寬度
///
/// - Parameters:
/// - height: 高度
/// - attributes: 屬性
/// - Returns: 返回的寬度
func getTextWidth(height: CGFloat,attributes: [TextAttributes]?) -> CGFloat {
let size = CGSize(width: 0, height: height)
let rect = getTextSize(string: self, size: size, attributes: attributes)
return rect.width
}
/// 轉(zhuǎn)換成不可變富文本
///
/// - Parameter attributes: 富文本屬性
/// - Returns: 不可變富文本
func conversion(attributes: [TextAttributes]?) -> NSAttributedString {
let attribute = configureAttributes(attributes: attributes)
let attributedString = NSAttributedString(string: self, attributes: attribute)
return attributedString
}
/// 轉(zhuǎn)換成可變富文本
///
/// - Parameter attributes: 富文本屬性
/// - Returns: 可變富文本
func conversionM(attributes: [TextAttributes]?) -> NSMutableAttributedString {
let attribute = configureAttributes(attributes: attributes)
let mutableAttributedString = NSMutableAttributedString(string: self, attributes: attribute)
return mutableAttributedString
}
/// 圖文混排
///
/// - Parameters:
/// - image: 圖標(biāo)
/// - bounds: 位置 (0,0,20,20)
/// - string: 文字
/// - textAttributes: 文字屬性
/// - Returns: 返回一個(gè)可變富文本
func imageWithText(image: UIImage, bounds:CGRect, string: String ,textAttributes: [TextAttributes]?) -> NSMutableAttributedString {
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = bounds
let mutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
let text:NSAttributedString = string.conversion(attributes: textAttributes)
mutableAttributedString.append(text)
return mutableAttributedString
}
/// 包含字串
///
/// - Parameters:
/// - pattern: 正則表達(dá)式
/// - Returns: true yes
func containsMatch(pattern: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, self.characters.count)
return (regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: range) != nil)
} catch _ {
fatalError( "rrror")
}
}
/// 高亮
///
/// - Parameters:
/// - pattern: 正則表達(dá)式
/// - attributes: 匹配到的字符屬性
/// - Returns: 返回新串
func highlightMatches(pattern: String, attributes: [TextAttributes]?) -> NSAttributedString {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, self.characters.count)
let matches = regex.matches(in: self, options: [], range: range)
let attributedText = NSMutableAttributedString(string: self)
let attribute = configureAttributes(attributes: attributes) ?? [:]
for match in matches {
attributedText.addAttributes(attribute, range: match.range)
}
return attributedText.copy() as! NSAttributedString
} catch _ {
fatalError( "字符串匹配錯(cuò)誤")
}
}
/// 匹配到的list
///
/// - Parameters:
/// - pattern: 正則表達(dá)式
/// - Returns: 返回匹配到的列表
func listMatches(pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, self.characters.count)
let matches = regex.matches(in: self, options: [], range: range)
return matches.map{
let range = $0.range
return NSString(string: self).substring(with: range)
}
} catch _ {
fatalError( "字符串匹配錯(cuò)誤")
}
}
func listGroups(pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, self.characters.count)
let matches = regex.matches(in: self, options: [], range: range)
var groupMatches = [String]()
for match in matches {
let rangeCount = match.numberOfRanges
for group in 0..<rangeCount {
let temp = NSString(string: self).substring(with: match.rangeAt(group))
groupMatches.append(temp)
}
}
return groupMatches
} catch _ {
fatalError( "字符串匹配錯(cuò)誤")
}
}
/// 替換字符
///
/// - Parameters:
/// - pattern: 正則表達(dá)式
/// - replacementString: 替換的字符
/// - Returns: 返回被替換后的字符串
func replaceMatches(pattern: String, withString replacementString: String) -> String? {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, self.characters.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacementString)
} catch _ {
fatalError("字符串匹配錯(cuò)誤")
}
}
}