iOS Swift 3.0 富文本

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ò)誤")
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市路狮,隨后出現(xiàn)的幾起案子虫啥,更是在濱河造成了極大的恐慌,老刑警劉巖奄妨,帶你破解...
    沈念sama閱讀 222,946評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件涂籽,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡展蒂,警方通過查閱死者的電腦和手機(jī)又活,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來锰悼,“玉大人柳骄,你說我怎么就攤上這事』悖” “怎么了耐薯?”我有些...
    開封第一講書人閱讀 169,716評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)丝里。 經(jīng)常有香客問我曲初,道長(zhǎng),這世上最難降的妖魔是什么杯聚? 我笑而不...
    開封第一講書人閱讀 60,222評(píng)論 1 300
  • 正文 為了忘掉前任臼婆,我火速辦了婚禮,結(jié)果婚禮上幌绍,老公的妹妹穿的比我還像新娘颁褂。我一直安慰自己,他們只是感情好傀广,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評(píng)論 6 398
  • 文/花漫 我一把揭開白布颁独。 她就那樣靜靜地躺著,像睡著了一般伪冰。 火紅的嫁衣襯著肌膚如雪誓酒。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,807評(píng)論 1 314
  • 那天贮聂,我揣著相機(jī)與錄音靠柑,去河邊找鬼。 笑死吓懈,一個(gè)胖子當(dāng)著我的面吹牛病往,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播骄瓣,決...
    沈念sama閱讀 41,235評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼停巷,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼耍攘!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起畔勤,我...
    開封第一講書人閱讀 40,189評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤蕾各,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后庆揪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體式曲,經(jīng)...
    沈念sama閱讀 46,712評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評(píng)論 3 343
  • 正文 我和宋清朗相戀三年缸榛,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吝羞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,926評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡内颗,死狀恐怖钧排,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情均澳,我是刑警寧澤恨溜,帶...
    沈念sama閱讀 36,580評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站找前,受9級(jí)特大地震影響糟袁,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜躺盛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評(píng)論 3 336
  • 文/蒙蒙 一项戴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧槽惫,春花似錦周叮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽槐臀。三九已至锄蹂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間水慨,已是汗流浹背得糜。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評(píng)論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留晰洒,地道東北人朝抖。 一個(gè)月前我還...
    沈念sama閱讀 49,368評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像谍珊,于是被迫代替她去往敵國和親治宣。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容