【发布时间】:2017-06-05 09:22:40
【问题描述】:
我有一个表格视图,其中的单元格内部只有一个标签,这没什么奇怪的。 我希望这个单个标签包含具有 2 种不同颜色的文本:
let red = NSAttributedString(string: "Red color",
attributes:
[NSForegroundColorAttributeName: UIColor.redColor(),
NSFontAttributeName: normalFont])
let blue = NSAttributedString(string: "Blue color",
attributes:
[NSForegroundColorAttributeName: UIColor.blueColor(),
NSFontAttributeName: boldFont])
let attributedText = NSMutableAttributedString(attributedString: red)
attributedText.appendAttributedString(blue)
self.labelInformation.attributedText = attributedText
问题:文字全是蓝色,我不明白为什么。
如果我打印出attributedText,我会得到:
Red color
{
NSColor = "UIExtendedSRGBColorSpace 1 0 0 1";
NSFont = "<UICTFont: 0x104249d80> font-family: \"Open Sans\"; font-weight: normal; font-style: normal; font-size: 18.00pt";
}Blue color{
NSColor = "UIExtendedSRGBColorSpace 0 0 1 1";
NSFont = "<UICTFont: 0x10b51d7c0> font-family: \"Open Sans\"; font-weight: bold; font-style: normal; font-size: 20.00pt";
}
好像没问题!
问题必须与表格视图相关,因为应用于视图的相同代码有效。
有什么建议吗?
更新
此代码位于自定义单元格视图的方法中:
class CustomViewCell: UITableViewCell {
func setup() {
// code above
}
}
在控制器中:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomIdentifier") as! CustomTableViewCell
cell.setup()
return cell
}
【问题讨论】:
-
当我在 swift 3.0 中编写此代码的等效代码时,它工作得很好。
-
这里也一样。确实在操场上工作 swift 3.
-
另外,在你发布这个sn-p之后是否有任何与
self.labelInformation相关的代码 -
你在哪里调用这个代码块?
CellForRow? -
是的,这段代码在 CustomCell 的 cellForRow 方法中调用
标签: ios objective-c swift xcode uilabel