2

Ich habe einige Suchoptionen in meiner App, die gegebenes Wort in UISearchBar hervorheben wird. Gegebenes Wort kann mehrere Male im Etikett vorkommen Ich muss alle diese Wörter markieren. Wie es möglich ist, habe ich mit einem gewissen Satz von Codes versucht, aber es wird nur ein Auftreten dieses Wort zu markieren, Hier ist mein Beispielcode ist:iOS Swift Änderung bestimmter Text Farbe innerhalb Label programmatisch

var SearchAttributeText = "The" 
let range = (TextValue as NSString).range(of: SearchAttributeText) 
let attribute = NSMutableAttributedString.init(string: TextValue) 
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red , range: range) 
self.label.attributedText = attribute 

Need mit beiden Upper und lower Fällen zu unterstützen. Word The kann mehrmals auftreten, müssen alle markieren.

+0

dieses Tutorial Siehe: https://iosdevcenters.blogspot.com/2015/12/how-to-set-use-multiple-font-colors-in.html – Bhadresh

+0

@Bhadresh Ich habe bereits dieses Blog verwiesen sie ändern Farbe basierend auf Bereich nicht basierend auf gegebenem Zeichen –

+0

Mit [this question] alle Bereiche des jeweiligen Substrings abrufen (https://stackoverflow.com/questions/36865443/get-all-ranges-of-a-substring-in-a-string-in-swift) und iteriere durch sie. – the4kman

Antwort

1

Sie können folgenden Code in Zeichenfolge

//Text need to be searched 
    let SearchAttributeText = "the" 

    //Store label text in variable as NSString 
    let contentString = lblContent.text! as NSString 

    //Create range of label text 
    var rangeString = NSMakeRange(0, contentString.length) 

    //Convert label text into attributed string 
    let attribute = NSMutableAttributedString.init(string: contentString as String) 

    while (rangeString.length != NSNotFound && rangeString.location != NSNotFound) { 

     //Get the range of search text 
     let colorRange = (lblContent.text?.lowercased() as! NSString).range(of: SearchAttributeText, options: NSString.CompareOptions(rawValue: 0), range: rangeString) 

     if (colorRange.location == NSNotFound) { 
      //If location is not present in the string the loop will break 
      break 
     } else { 
      //This line of code colour the searched text 
      attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: colorRange) 
      lblContent.attributedText = attribute 

      //This line of code increment the rangeString variable 
      rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length)) 
     } 
    } 

Die folgende Codezeile Update zu suchen, der Bereich durch die location und length Parameter des Inkrementierens NSRange

rangeString = NSMakeRange(colorRange.location + colorRange.length, contentString.length - (colorRange.location + colorRange.length)) 
Verwandte Themen