更改文本视图中文本的颜色
Change colour of text in textview
我有一个组合了多个字符串的文本视图,每个字符串由一个新行分隔。每个字符串还有一个标题,我想用不同的颜色显示并加粗。
我目前的代码如下:
let summaryText = "Summary \n"
let summaryAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
let summaryString = NSAttributedString(string: summaryText, attributes:summaryAttributes)
GoalSettingDetailsTextView.attributedText = summaryString + GoalSettingMoreDetailsSummary + "\n\n" + "Notes \n" + GoalSettingMoreDetailsNotes
在这里您可以看到我已经尝试将 "Summary" 设为橙色。我还尝试将 "Notes" 标题显示为没有任何属性的普通字符串。这部分工作正常。但是,我收到 "summaryString" 的错误。
错误是:
Binary operator '+' cannot be applied to operands of type 'NSAttributedString' and 'String'
我怎样才能让它工作?
您不能使用 +
附加 NSAttributedString
。
创建一个 NSMutableAttributedString
并构建它。
let attrStr = NSMutableAttributedString(attributedString: summaryString)
attrStr.append(GoalSettingMoreDetailsSummary) // not sure what GoalSettingMoreDetailsSummary is
attrStr.append(NSAttributedString(string: "\n\nNotes \n"))
attrStr.append(GoalSettingMoreDetailsNotes) // not sure what GoalSettingMoreDetailsNotes is
GoalSettingDetailsTextView.attributedText = attrStr
此代码假定 GoalSettingMoreDetailsSummary
和 GoalSettingMoreDetailsNotes
的类型为 NSAttributedString
。如果它们只是 String
然后从它们创建 NSAttributedString
就像我对文字字符串所做的那样。
看看Prestyler。你可以这样写:
Prestyler.defineRule("$", Prestyle.bold, UIColor.red)
label.attributedText = ("$My title$" + nextText).prestyled
我有一个组合了多个字符串的文本视图,每个字符串由一个新行分隔。每个字符串还有一个标题,我想用不同的颜色显示并加粗。
我目前的代码如下:
let summaryText = "Summary \n"
let summaryAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
let summaryString = NSAttributedString(string: summaryText, attributes:summaryAttributes)
GoalSettingDetailsTextView.attributedText = summaryString + GoalSettingMoreDetailsSummary + "\n\n" + "Notes \n" + GoalSettingMoreDetailsNotes
在这里您可以看到我已经尝试将 "Summary" 设为橙色。我还尝试将 "Notes" 标题显示为没有任何属性的普通字符串。这部分工作正常。但是,我收到 "summaryString" 的错误。
错误是:
Binary operator '+' cannot be applied to operands of type 'NSAttributedString' and 'String'
我怎样才能让它工作?
您不能使用 +
附加 NSAttributedString
。
创建一个 NSMutableAttributedString
并构建它。
let attrStr = NSMutableAttributedString(attributedString: summaryString)
attrStr.append(GoalSettingMoreDetailsSummary) // not sure what GoalSettingMoreDetailsSummary is
attrStr.append(NSAttributedString(string: "\n\nNotes \n"))
attrStr.append(GoalSettingMoreDetailsNotes) // not sure what GoalSettingMoreDetailsNotes is
GoalSettingDetailsTextView.attributedText = attrStr
此代码假定 GoalSettingMoreDetailsSummary
和 GoalSettingMoreDetailsNotes
的类型为 NSAttributedString
。如果它们只是 String
然后从它们创建 NSAttributedString
就像我对文字字符串所做的那样。
看看Prestyler。你可以这样写:
Prestyler.defineRule("$", Prestyle.bold, UIColor.red)
label.attributedText = ("$My title$" + nextText).prestyled