2014-09-17 23 views
5

UITableView var ve her satırın metnini aynı satır içinde farklı renkler kullanarak görüntülemek istiyorum.NSMutableAttributedStrings kullanarak metnin rengini hızlı değiştirin

Ben Obj-C'den çevirmek için çalışıyor, bu kodu denedim ama ben

 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 

çalışma olamaz Bütün bunların çıkış sayısı 34 object.valueForKey("example1")!.description karşılık enter image description here

olduğunu Bu nedenle sorun, sayı kırmızı değil ve ikinci kısım (object.valueForKey("example2")!.description) { ile değiştirilmiştir.

NSAttributedString ile ilgili bu koddan ayrılırsam satır metni doğru görüntülenir.

cevap

11

Sorunun, cell.textLabel?.attributedText yerine cell.textLabel?.text'a atanmasında sorun olabileceğini düşünüyorum. Böyle Belki bir şey: Eğer dize ikinci bölümü kırmızı olmak istedim ya da başka bir renk yüzden siyah yaptıysam

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 

emin değildi. Eğer NSMutableAttributedString kullanmaktan kaçınmak ve sadece yapıcı özniteliklerde geçebilir

1

: Burada

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

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 
Swift 3 özellik bir metin örneğidir
İlgili konular