Search code examples
swifttextviewnsattributedstring

Change colour of text in textview


I've got a textview that combines several strings, each separated by a new line. Each string also has a title, which I'd like to display in a different colour and bolded.

The code I have so far is as follows:

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

Here you can see that I've tried to make "Summary" orange. I've also tried to display the "Notes" title as a normal string without any attributers. This part works fine. However, I get an error with "summaryString".

The error is:

Binary operator '+' cannot be applied to operands of type 'NSAttributedString' and 'String'

How can I get this working?


Solution

  • You can't use + to append with NSAttributedString.

    Create an NSMutableAttributedString and build that up.

    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
    

    This code assumes GoalSettingMoreDetailsSummary and GoalSettingMoreDetailsNotes are of type NSAttributedString. If they are just String then create NSAttributedString from them like I did with the literal string.