Etichetta con testo di due diversi colori


109

Voglio visualizzare una stringa come questa in a UILabel:

Ci sono 5 risultati.

Dove il numero 5 è di colore rosso e il resto della stringa è nero.

Come posso farlo in codice?


6
@EmptyStack Questo è certamente non è il caso, in quanto iOS 4 supporti NSAttributedString. Vedi la mia risposta di seguito.
— Mic Pringle

Risposte:


223

Il modo per farlo è usare in NSAttributedStringquesto modo:

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

Ho creato UILabel un'estensione per farlo .


Posso aggiungere obiettivi su di esso. Thnaks
— UserDev

Ho appena aggiunto la tua estensione al mio progetto! Grazie!
— Zeb il

Bella categoria per UILabel. Molte grazie. Questa dovrebbe essere la risposta accettata.
— Pradeep Reddy Kypa

63

L'ho fatto creando un categoryperNSMutableAttributedString

-(void)setColorForText:(NSString*) textToFind withColor:(UIColor*) color
{
    NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch];

    if (range.location != NSNotFound) {
        [self addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
}

Usalo come

- (void) setColoredLabel
{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Here is a red blue and green text"];
    [string setColorForText:@"red" withColor:[UIColor redColor]];
    [string setColorForText:@"blue" withColor:[UIColor blueColor]];
    [string setColorForText:@"green" withColor:[UIColor greenColor]];
    mylabel.attributedText = string;
}

SWIFT 3

extension NSMutableAttributedString{
    func setColorForText(_ textToFind: String, with color: UIColor) {
        let range = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        }
    }
}

USO

func setColoredLabel() {
    let string = NSMutableAttributedString(string: "Here is a red blue and green text")
    string.setColorForText("red", with: #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1))
    string.setColorForText("blue", with: #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1))
    string.setColorForText("green", with: #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1))
    mylabel.attributedText = string
}

SWIFT 4 @ kj13 Grazie per la notifica

// If no text is send, then the style will be applied to full text
func setColorForText(_ textToFind: String?, with color: UIColor) {

    let range:NSRange?
    if let text = textToFind{
        range = self.mutableString.range(of: text, options: .caseInsensitive)
    }else{
        range = NSMakeRange(0, self.length)
    }
    if range!.location != NSNotFound {
        addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range!)
    }
}

Ho fatto più esperimenti con gli attributi e di seguito sono riportati i risultati, ecco il SOURCECODE

Ecco il risultato

stili


2
Devi creare una nuova categoria per NSMutableAttributedString con il metodo ... comunque ho aggiunto questo esempio a github, puoi prenderlo e controllarlo github.com/anoop4real/NSMutableAttributedString-Color
— anoop4real

Ma devo impostare il colore di tutto l'alfabeto con incasensibile in una stringa .... come tutte le "e" in rosso dell'intera stringa
— Ravi Ojha

Nessuna interfaccia @ visibile per 'NSMutableAttributedString' dichiara il selettore 'setColorForText: withColor:'
— ekashking

1
Ho ricevuto l'errore "Uso dell'identificatore non risolto" NSForegroundColorAttributeName "con Swift4.1, ma sostituisco" NSForegroundColorAttributeName "con" NSAttributedStringKey.foregroundColor "e la creazione è corretta.
— kj13

1
@ kj13 Grazie per la notifica, ho aggiornato la risposta e aggiunto alcuni altri stili
— anoop4real

25

Ecco qui

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:lblTemp.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
lblTemp.attributedText = string;

20

Swift 4

// An attributed string extension to achieve colors on text.
extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {
       let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
       self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

// Try it with label
let label = UILabel()
label.frame = CGRect(x: 70, y: 100, width: 260, height: 30)
let stringValue = "There are 5 results."
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: "5")
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

Risultato

inserisci qui la descrizione dell'immagine


Swift 3

func setColoredLabel() {
        var string: NSMutableAttributedString = NSMutableAttributedString(string: "redgreenblue")
        string.setColor(color: UIColor.redColor(), forText: "red")
        string.setColor(color: UIColor.greenColor(), forText: "green")
        string.setColor(color: UIColor.blueColor(, forText: "blue")
        mylabel.attributedText = string
    }


func setColor(color: UIColor, forText stringValue: String) {
        var range: NSRange = self.mutableString.rangeOfString(stringValue, options: NSCaseInsensitiveSearch)
        if range != nil {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        }
    }

Risultato:

inserisci qui la descrizione dell'immagine


12
//NSString *myString = @"I have to replace text 'Dr Andrew Murphy, John Smith' ";
NSString *myString = @"Not a member?signin";

//Create mutable string from original one
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:myString];

//Fing range of the string you want to change colour
//If you need to change colour in more that one place just repeat it
NSRange range = [myString rangeOfString:@"signin"];
[attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:(63/255.0) green:(163/255.0) blue:(158/255.0) alpha:1.0] range:range];

//Add it to the label - notice its not text property but it's attributeText
_label.attributedText = attString;

6

Da iOS 6 , UIKit supporta il disegno di stringhe attribuite, quindi non è necessaria alcuna estensione o sostituzione.

Da UILabel:

@property(nonatomic, copy) NSAttributedString *attributedText;

Hai solo bisogno di costruire il tuo NSAttributedString. Esistono fondamentalmente due modi:

  1. Aggiungi porzioni di testo con gli stessi attributi: per ogni parte crea NSAttributedStringun'istanza e aggiungile a unaNSMutableAttributedString

  2. Crea un testo attribuito da una stringa semplice e quindi aggiungi attribuito per determinati intervalli: trova l'intervallo del tuo numero (o qualsiasi altra cosa) e applica un attributo di colore diverso su quello.


6

Anups risponde rapidamente. Può essere riutilizzato da qualsiasi classe.

In un file rapido

extension NSMutableAttributedString {

    func setColorForStr(textToFind: String, color: UIColor) {

        let range = self.mutableString.rangeOfString(textToFind, options:NSStringCompareOptions.CaseInsensitiveSearch);
        if range.location != NSNotFound {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range);
        }

    }
}

In alcuni view controller

let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.labelShopInYourNetwork.text!);
attributedString.setColorForStr("YOUR NETWORK", color: UIColor(red: 0.039, green: 0.020, blue: 0.490, alpha: 1.0));
self.labelShopInYourNetwork.attributedText = attributedString;

4

Avere un UIWebView o più di un UILabel potrebbe essere considerato eccessivo per questa situazione.

Il mio suggerimento sarebbe quello di utilizzare TTTAttributedLabel, che è un sostituto immediato per UILabel che supporta NSAttributedString . Ciò significa che puoi applicare molto facilmente stili diversi a intervalli diversi in una stringa.




3

JTAttributedLabel (di mystcolor) ti consente di utilizzare il supporto delle stringhe attribuite in UILabel sotto iOS 6 e allo stesso tempo la sua classe JTAttributedLabel sotto iOS 5 attraverso il suo JTAutoLabel.


2

C'è una soluzione Swift 3.0

extension UILabel{


    func setSubTextColor(pSubString : String, pColor : UIColor){
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!);
        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString

    }
}

E c'è un esempio di chiamata:

let colorString = " (string in red)"
self.mLabel.text = "classic color" + colorString
self.mLabel.setSubTextColor(pSubString: colorString, pColor: UIColor.red)

Ciao, come faccio se voglio aggiungere due colorString differenti? Ho provato a usare il tuo esempio e aggiungerne un altro, ma ne colora ancora solo uno ..
— Erik Auranaune

Prova questo: let colorString = "(stringa in rosso)" let colorStringGreen = "(stringa in verde)" self.mLabel.text = "colore classico" + colorString + colorStringGreen self.mLabel.setSubTextColor (pSubString: colorString, pColor: UIColor .red) self.mLabel.setSubTextColor (pSubString: colorStringGreen, pColor: UIColor.green)
— Kevin ABRIOUX

Questo è strano, ancora non cambia entrambi: s24.postimg.org/ds0rpyyut/… .
— Erik Auranaune

Un problema è che se le due stringhe sono uguali, ne colora solo una, guarda qui: pastebin.com/FJZJTpp3 . Hai una soluzione anche per questo?
— Erik Auranaune

2

Swift 4 e versioni successive: ispirata alla soluzione di anoop4real , ecco un'estensione String che può essere utilizzata per generare testo con 2 colori diversi.

extension String {

    func attributedStringForPartiallyColoredText(_ textToFind: String, with color: UIColor) -> NSMutableAttributedString {
        let mutableAttributedstring = NSMutableAttributedString(string: self)
        let range = mutableAttributedstring.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            mutableAttributedstring.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
        }
        return mutableAttributedstring
    }
}

L'esempio seguente cambia il colore dell'asterisco in rosso mantenendo il colore dell'etichetta originale per il testo rimanente.

label.attributedText = "Enter username *".attributedStringForPartiallyColoredText("*", with: #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1))

2

La mia risposta ha anche la possibilità di colorare tutte le occorrenze di un testo non solo una occorrenza di esso: "wa ba wa ba dubdub", puoi colorare tutte le occorrenze di wa non solo la prima occorrenza come la risposta accettata.

extension NSMutableAttributedString{
    func setColorForText(_ textToFind: String, with color: UIColor) {
        let range = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        if range.location != NSNotFound {
            addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        }
    }

    func setColorForAllOccuranceOfText(_ textToFind: String, with color: UIColor) {
        let inputLength = self.string.count
        let searchLength = textToFind.count
        var range = NSRange(location: 0, length: self.length)

        while (range.location != NSNotFound) {
            range = (self.string as NSString).range(of: textToFind, options: [], range: range)
            if (range.location != NSNotFound) {
                self.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            }
        }
    }
}

Ora puoi farlo:

let message = NSMutableAttributedString(string: "wa ba wa ba dubdub")
message.setColorForText(subtitle, with: UIColor.red) 
// or the below one if you want all the occurrence to be colored 
message.setColorForAllOccuranceOfText("wa", with: UIColor.red) 
// then you set this attributed string to your label :
lblMessage.attributedText = message

E come posso usarlo?
— pableiros

1
Aggiornata la mia risposta, buona giornata :)
— Compilatore Alsh

1

Per utenti Xamarin ho un metodo C # statico in cui passo una matrice di stringhe, una matrice di UIColours e una matrice di UIFont (dovranno corrispondere in lunghezza). La stringa attribuita viene quindi restituita.

vedere:

public static NSMutableAttributedString GetFormattedText(string[] texts, UIColor[] colors, UIFont[] fonts)
    {

        NSMutableAttributedString attrString = new NSMutableAttributedString(string.Join("", texts));
        int position = 0;

        for (int i = 0; i < texts.Length; i++)
        {
            attrString.AddAttribute(new NSString("NSForegroundColorAttributeName"), colors[i], new NSRange(position, texts[i].Length));

            var fontAttribute = new UIStringAttributes
            {
                Font = fonts[i]
            };

            attrString.AddAttributes(fontAttribute, new NSRange(position, texts[i].Length));

            position += texts[i].Length;
        }

        return attrString;

    }

1

Nel mio caso sto usando Xcode 10.1. È disponibile un'opzione per passare dal testo normale al testo attribuito nel testo dell'etichetta in Interface Builder

inserisci qui la descrizione dell'immagine

Spero che questo possa aiutare qualcun altro ..!


2
Sembra che XCode 11.0 abbia rotto l'editor di testo attribuito. Quindi, ho provato a utilizzare TextEdit per creare il testo, quindi l'ho incollato in Xcode e ha funzionato sorprendentemente bene.
— Brainware

0
extension UILabel{

    func setSubTextColor(pSubString : String, pColor : UIColor){


        let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);


        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString

    }
}

0

La mia soluzione è stata creata con un metodo come il prossimo:

-(void)setColorForText:(NSString*) textToFind originalText:(NSString *)originalString withColor:(UIColor*)color andLabel:(UILabel *)label{

NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:originalString];
NSRange range = [originalString rangeOfString:textToFind];

[attString addAttribute:NSForegroundColorAttributeName value:color range:range];

label.attributedText = attString;

if (range.location != NSNotFound) {
    [attString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
label.attributedText = attString; }

Funzionava con un solo colore diverso nello stesso testo, ma puoi adattarlo facilmente a più colori nella stessa frase.


0

Utilizzando il codice sottostante è possibile impostare più colori in base alla parola.

NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];    
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
    NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
     [attStr appendAttributedString:textstr];
  }
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];

-(UIColor *) getRandomColor
{
   CGFloat redcolor = arc4random() % 255 / 255.0;
   CGFloat greencolor = arc4random() % 255 / 255.0;
   CGFloat bluencolor = arc4random() % 255 / 255.0;
   return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.