2017-07-05 1 views

Répondre

1
extension NSAttributedString { 

    func replaceHTMLTag(tag: String, withAttributes attributes: [String: AnyObject]) -> NSAttributedString { 
     let openTag = "<\(tag)>" 
     let closeTag = "</\(tag)>" 

     let resultingText: NSMutableAttributedString = self.mutableCopy() as! NSMutableAttributedString 
     while true { 
      let plainString = resultingText.string as NSString 
      let openTagRange = plainString.range(of: openTag) 
      if openTagRange.length == 0 { 
       break 
      } 

      let affectedLocation = openTagRange.location + openTagRange.length 

      let searchRange = NSRange(location: affectedLocation, length: plainString.length - affectedLocation) 

      let closeTagRange = plainString.range(of: closeTag, options: NSString.CompareOptions.init(rawValue: 0), range: searchRange) 

      resultingText.setAttributes(attributes, range: NSRange(location: affectedLocation, length: closeTagRange.location - affectedLocation)) 
      resultingText.deleteCharacters(in: closeTagRange) 
      resultingText.deleteCharacters(in: openTagRange) 
     } 
     return resultingText as NSAttributedString 
    } 
} 
+0

Je reçois l'erreur suivante avec Xcode9 (Swift4): Impossible de convertir la valeur de type « [chaîne: ANYOBJECT] » au type d'argument attendu '[NSAttributedStringKey: Any]?' Résolu avec: https://stackoverflow.com/questions/45695286/cannot-convert-value-of-type-string-anyobject-to-expected-argument-type – Dorad

0

Vous devez supprimer les ancres^et $. Le^signifie début de chaîne et $ signifie fin de chaîne (ou ligne, selon les options). C'est pourquoi votre premier exemple fonctionne: dans la première chaîne de test, le début de la chaîne est vraiment suivi par votre modèle et se termine avec.

Dans la deuxième chaîne de test, le motif se trouve au milieu de la chaîne, ainsi le^... ne peut pas s'appliquer. Si vous supprimiez juste le ^, le $ s'appliquerait sur la deuxième occurrence du numéro d'enregistrement et la sortie serait ma voiture reg 1 - DD11 AAA ma voiture reg 2 - XX.

let myString = "my car reg 1 - DD11 AAA my car reg 2 - AA22 BBB" 
let regex = try! NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options:  NSRegularExpressionOptions.CaseInsensitive) 
let range = NSMakeRange(0, myString.characters.count) 
let modString = regex.stringByReplacingMatchesInString(myString, options: [], range: range, withTemplate: "XX") 
print(modString) 
// Output: "my car reg 1 - XX my car reg 2 - XX" 

Référence: https://stackoverflow.com/a/28503676/8169585

0

Essayez cette extension. Il va convertir la chaîne HTML en NSAttributtedString. I a également le rapport de 0,75 appliqué en raison du fait que la conversion par défaut augmente toute la taille de la police

extension String { 
    func htmlAttributedString() -> NSAttributedString? { 
     guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil } 
     guard let html = try? NSMutableAttributedString(
      data: data, 
      options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
      documentAttributes: nil) else { return nil } 
     html.beginEditing() 
     html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: .init(rawValue: 0)) { 
      (value, range, stop) in 
      if let font = value as? UIFont { 
       let resizedFont = font.withSize(font.pointSize * 0.75) 
       html.addAttribute(NSFontAttributeName, 
             value: resizedFont, 
             range: range) 
      } 
     } 
     html.endEditing() 
     return html 
    } 
}