Search code examples
iosjsonstringswift3nsattributedstring

Replace attributed string into NSMutableAttributedString In Swift 3


I want to output like

My name is Pramod Tapaniya

from below json.

{
    "text": "My name is B0$ Tapaniya.",
    "formats": {
            "formatId": [
                "B0$"
            ],
            "formatValue": [
                "Pramod"
            ]
    }
}

I have tried below code, but getting compile time error because I replacing String with Attributed String. I have used SwiftyJson for handle json.

let boldAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 13)]
let simpleAttributes = [NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.systemFont(ofSize: 13)]

let strComm = NSMutableAttributedString(string: dict["text"].stringValue, attributes: simpleAttributes)
let attributedStr = NSMutableAttributedString()

attributedStr.append(strComm)

let arrFormatId = dict["formats"]["formatId"]
let arrFormatValue = dict["formats"]["formatValue"]

for var i in 0..<arrFormatId.count{
    let strBold = NSMutableAttributedString(string: arrFormatValue[i].stringValue, attributes: boldAttributes)
    attributedStr.mutableString.replaceOccurrences(of: arrFormatId[i].stringValue, with: strBold, options: .caseInsensitive, range: NSRange(location: 0, length: attributedStr.length)) //Cannot convert value of type 'NSMutableAttributedString' to expected argument type 'String'
}
return attributedStr

Solution

  • replace with this code

    let boldAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 13)]
    let simpleAttributes = [NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.systemFont(ofSize: 13)]
    
    let strComm = NSMutableAttributedString(string: dict["text"].stringValue, attributes: simpleAttributes)
    let attributedStr = NSMutableAttributedString()
    
    attributedStr.append(strComm)
    
    let arrFormatId = dict["formats"]["formatId"]
    let arrFormatValue = dict["formats"]["formatValue"]
    
    for var i in 0..<arrFormatId.count{
        let strBold = NSMutableAttributedString(string: arrFormatValue[i].stringValue, attributes: boldAttributes)
        while attributedStr.mutableString.contains(arrFormatId[i].stringValue) {
            let range = attributedStr.mutableString.range(of: arrFormatId[i].stringValue)
            attributedStr.replaceCharacters(in: range, with: strBold)
        }
    }
    return attributedStr