【问题标题】:Replace attributed string into NSMutableAttributedString In Swift 3在 Swift 3 中将属性字符串替换为 NSMutableAttributedString
【发布时间】:2018-02-05 08:11:51
【问题描述】:

我想像这样输出

我的名字是 Pramod 塔帕尼亚

从下面的 json.

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

我尝试了下面的代码,但是因为我用属性字符串替换了字符串,所以出现了编译时错误。我使用 SwiftyJson 处理 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

【问题讨论】:

    标签: ios json string swift3 nsattributedstring


    【解决方案1】:

    用这个代码替换

    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
    

    【讨论】:

      【解决方案2】:

      简单的解决方案是

      var text = "My name is B0$ Tapaniya"
      var arrayID = ["B0$"]
      
      var arrayValue =  ["Pramod"]
      
      if arrayID.count == arrayValue.count {
          for key in arrayID {
              text = text.replacingOccurrences(of: key, with:arrayValue[arrayID.index(of: key)!])
          }
      
       // Now use below methods
      
          let formattedString = NSMutableAttributedString()
          formattedString
         .normal(text)
         .bold(arrayValue.joined(separator: ","))   
      
      }
      

      来自https://stackoverflow.com/a/37992022/4601900

      extension NSMutableAttributedString {
          @discardableResult func bold(_ text:String) -> NSMutableAttributedString {
              let attrs = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 13)]
      
              let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs)
              self.append(boldString)
              return self
          }
      
          @discardableResult func normal(_ text:String)->NSMutableAttributedString {
              let normal =  NSAttributedString(string: text)
              self.append(normal)
              return self
          }
      }
      

      【讨论】:

        【解决方案3】:

        请试试这个:

        var testDict = ["text": "My name is B0$ Tapaniya.","formats": ["formatId": ["B0$"],"formatValue": ["Pramod"]]] as [String : AnyObject]
        let attrString = NSMutableAttributedString(string: testDict["text"] as! String)
        var formatIDS = testDict["formats"]?.value(forKey: "formatId") as! [String]
        var formatValues = testDict["formats"]?.value(forKey: "formatValue") as! [String]
        
        for i in 0..<formatIDS.count {
            attrString.mutableString.replaceOccurrences(of: formatIDS[i], with: formatValues[i], options: NSString.CompareOptions.caseInsensitive, range: NSRange(location: 0, length: attrString.length))
            attrString.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12.0)], range: attrString.mutableString.range(of: formatValues[i] as String))
        }
        print(attrString)
        

        【讨论】:

        • “Pramod”为粗体。您只需替换字符串。
        • 更新了答案。
        猜你喜欢
        • 2015-06-20
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多