我有一个UITableView,我想在同一行中使用不同的颜色显示每行的文本.
我试过这个代码,尝试从Obj-C翻译,但我不能让它工作
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
这一切的输出是
其中数字34对应于object.valueForKey(“example1”)!. description,所以问题是数字不是红色,而第二部分(object.valueForKey(“example2”)!.description)被替换为{ .
解决方法
我认为问题可能在于分配给cell.textLabel?.text而不是cell.textLabel?.attributedText.也许是这样的:
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description) attrString.addAttribute(NSForegroundColorAttributeName,attrString.length)) var descString: NSMutableAttributedString = NSMutableAttributedString(string: String(format: " %@",object.valueForKey("example2")!.description)) descString.addAttribute(NSForegroundColorAttributeName,value: UIColor.blackColor(),descString.length)) attrString.appendAttributedString(descString); cell.textLabel?.attributedText = attrString
不确定你是否希望字符串的第二部分是红色或其他颜色,所以我把它变黑了.