Swift:Range和NSRange問題

本文下方封裝了簡單的屬性字符串方法。封裝中只實現(xiàn)了最基礎(chǔ)的功能,用來設(shè)置一個string中的某些subString特殊顯示。調(diào)用方法為鏈式調(diào)用。

---> 下面來說說使用NSMutableAttributeString遇到的問題

要特殊顯示的subString可以調(diào)用

open func addAttributes(_ attrs: [String : Any] = [:], range: NSRange)

來設(shè)置,注意這里的range類型是NSRange,我們在獲取這個range的時候想當然會這樣做:

//其實這時候獲取的range類型是Range
let range = attributeStr.string.range(of: "subString")

Range是無法通過 as? 強制轉(zhuǎn)換到NSRange的。

方式1. 比較簡單的處理方式就是

//1.先把String轉(zhuǎn)換成 NSStiring
let nsString = NSString(string: attributeStr.string)

//2.NSString中的range方法獲取到的是NSRange類型
let nsRange = nsString.range(of: "subString")

方式2. 另外比較復雜的處理就是把Range轉(zhuǎn)換成NSRange了:

//range轉(zhuǎn)換為NSRange  
//擴展的是String類,不可改為NSRange或者Range的擴展,因為samePosition,utf16是String里的
extension String {
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
}
//NSRange轉(zhuǎn)化為range
//擴展的是String類,不可改為NSRange或者Range的擴展,因為utf16是String里的
extension String {
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            else { return nil }
        return from ..< to
    }
}

我的CSDN上同步更新了本文章,點擊查看

最終代碼:Github代碼地址

import Foundation
import UIKit
class TAttributeString {
    
    var attributeStr : NSMutableAttributedString =  NSMutableAttributedString()
    
    //設(shè)置整體的字符串
    func setString(string: String,color: UIColor, fontSize: CGFloat) -> Self {
        
        return setString(string: string, color: color, font: UIFont.systemFont(ofSize: fontSize))
    }
    
    func setString(string: String, color: UIColor, font: UIFont) -> Self {
        
        let inceptionAttStr = NSAttributedString(string: string, attributes: [NSFontAttributeName:font,NSForegroundColorAttributeName:color])
        
        attributeStr.setAttributedString(inceptionAttStr)
        
        return self
    }
}

//設(shè)置屬性字符串中的 特殊顯示的字符
extension TAttributeString {
    
    func height(string: String, color: UIColor) -> Self {
        let nsString = NSString(string: attributeStr.string)
        
        attributeStr.setAttributes([NSForegroundColorAttributeName:color], range: nsString.range(of: string))
        
        return self
    }
    
    func height(string: String, color: UIColor, fontSize: CGFloat) -> Self {
        
        return height(string: string, color: color, font: UIFont.systemFont(ofSize: fontSize))
    }
    
    func height(string: String, color: UIColor, font: UIFont) -> Self {
        
        let nsString = NSString(string: attributeStr.string)
        
        attributeStr.setAttributes([NSFontAttributeName:font, NSForegroundColorAttributeName:color], range: nsString.range(of: string))
        
        return self
    }
    
}

調(diào)用方式

 label.attributedText = TAttributeString().setString(string: "swift:這里只是封裝了最常用的功能,采用簡單的鏈式調(diào)用,核心方法很少,都是一些方便調(diào)用的衍生方法", color: UIColor.black, fontSize: 14).height(string: "swift:", color: UIColor.red, fontSize: 20).height (string: "鏈式調(diào)用", color: UIColor.blue, font: UIFont.boldSystemFont(ofSize: 10)).attributeStr

效果:

效果展示
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容