2017-06-18 3 views
0

J'essaie de trouver NSRange de plusieurs chaînes dans une chaîne.Recherche des occurrences de chaîne comme NSRange à partir d'un NSString en utilisant Swift, résultat NSRange à utiliser dans NSAttributedString

Dans mon code suivant, j'utilise la méthode String.range(of: String, options: , Range) pour trouver Range et le convertir en NSRange. cette conversion échoue lorsque le texte contient l'unité multi-codes de caractères unicode, comme emoji:

let findInString = "This #is a #tag #tag inten#sive#search" // MAY CONTAINS EMOJIS 
let findStrings = ["#is","#tag","#sive","#search"] 
let result = NSMutableAttributedString(string: findInString) 

for (index, stringToFind) in findStrings.enumerated() { 

    var nextStartIndex = findInString.startIndex 

    while let range = findInString.range(of: stringToFind, options: [.literal, .caseInsensitive], range: nextStartIndex..<findInString.endIndex) { 

     let start = findInString.distance(from: findInString.startIndex, to: range.lowerBound) 
     let length = findInString.distance(from: range.lowerBound, to: range.upperBound) 

     result.addAttribute(NSLinkAttributeName, value: "\(index):", range: NSMakeRange(start, length)) 

     nextStartIndex = range.upperBound 
    } 

} 

Question: Est-il travailler Si je NSString.range() pour trouver NSRange. J'essaye ceci, mais mon code suivant ont une erreur dans la partie range:.

let findInNsString = findInString as NSString 
while let range = findInNsString.range(of: stringToFind, options: [.literal, .caseInsensitive], range: nextStartIndex..<findInString.endIndex) 

J'ai besoin d'aide pour comprendre et corriger l'erreur ci-dessus, merci d'avance.

Répondre

0

trouvé la bonne façon de convertir un Range à NSRange, grâce à MartinR pour cette answer

j'utilisais la mauvaise façon de convertir Range-NSRange, voici l'extrait de code de travail avec bonne façon de convertir Range à NSRange:

let findStrings = ["#is","#tag","#siØve","#search"] 
let findInString = "This #is a #tag #tag inten#siØve#search" 
let result = NSMutableAttributedString(string: findInString) 
let utf16 = findInString.utf16 
for (index, stringToFind) in findStrings.enumerated() { 

    var nextStartIndex = findInString.startIndex 

    while let range = findInString.range(of: stringToFind, options: [.literal, .caseInsensitive], range: nextStartIndex..<findInString.endIndex) { 

     // PROPER WAY TO CONVERT TO NSRange 
     let from = range.lowerBound.samePosition(in: utf16) 
     let start = utf16.distance(from: utf16.startIndex, to: from) 
     let length = utf16.distance(from: from, to: range.upperBound.samePosition(in: utf16)) 

     result.addAttribute(NSLinkAttributeName, value: "\(index):", range: NSMakeRange(start, length)) 

     nextStartIndex = range.upperBound 
    } 

}