2014-09-17 27 views
5

Mam UITableView i chciałbym wyświetlić tekst każdego wiersza za pomocą różnych kolorów w obrębie tej samej linii.Swift zmienić kolor tekstu za pomocą NSMutableAttributedStrings

Próbowałem ten kod, starając się tłumaczyć z Obj-C, ale nie mogę mieć to działa

 let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject 

     var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description) 
     attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length)) 

     var stringToCell:String = String(format: "%@ %@", attrString, object.valueForKey("example2")!.description) 
     cell.textLabel?.text = stringToCell 

Wyjście to wszystko enter image description here

gdzie liczba 34 odpowiada object.valueForKey("example1")!.description , więc problem polega na tym, że numer jest nie czerwony, a druga część (object.valueForKey("example2")!.description) jest zastąpiona przez {.

Jeśli zostawiam ten fragment kodu w odniesieniu do NSAttributedString, tekst wiersza zostanie wyświetlony poprawnie.

Odpowiedz

11

Myślę, że problem może polegać na przypisaniu do cell.textLabel?.text zamiast cell.textLabel?.attributedText. Może coś takiego:

let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject 

var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description) 
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length)) 

var descString: NSMutableAttributedString = NSMutableAttributedString(string: String(format: " %@", object.valueForKey("example2")!.description)) 
descString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, descString.length)) 

attrString.appendAttributedString(descString); 
cell.textLabel?.attributedText = attrString 

nie był pewien, czy chciał druga część napisu być czerwony lub inny kolor, więc zrobiłem to czarny.

1

Jeśli możesz, unikaj NSMutableAttributedString i po prostu przejść w atrybutach z konstruktora:

private func PullToRefreshAttributedStringWithColor(color:UIColor) -> NSAttributedString { 
    return NSAttributedString(string: "Pull to Refresh", attributes: [ 
     NSForegroundColorAttributeName:color 
    ]) 
} 
1

Oto przykład tekstu atrybutu Swift 3

let mainText = "Here is a example of attributedString" 
let attributeText = "attributedString" 
let range = (mainText as NSString).range(of: attributeText) 
let attributedString = NSMutableAttributedString(string:mainText) 

attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range) 
attribute.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: range) 

lblTitle.attributedText = attributedString