2

I am getting the error:

Cannot assign value of type 'NSMutableAttributedString' to type 'String?'

when trying to put the string into a UITextView.

I have read the following article: https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example which indicates that NSAttributedString can be used with UITextView. I have also tried to convert the NSMutuableAttributedString into a String as follows:

self.text.text = String(attributedQuote)

However, this did not work.

This assigns the 'transcription' as the string to be converted to NSMutableAttributedString:

let attributedQuote = NSMutableAttributedString(string: transcription)

This adds underlining to the first word in the attributedQuote:

attributedQuote.addAttribute(.underlineStyle, value: true, range: NSRange(location: 0, length: 4))

This adds the attributedQuote to the UITextView:

self.text.text = attributedQuote

Unfortunately, I'm getting the error when I was expecting the first word to be underlined.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Zenman C
  • 1,653
  • 13
  • 21
  • 1
    Please look at the documentation for `UITextView`. Find the property with a type of `NSAttributedString`. – rmaddy Apr 19 '19 at 03:11
  • https://developer.apple.com/documentation/uikit/uitextview/1618626-attributedtext - Thanks I checked the documentation and now have amended the code to: self.text.attributedText = attributedQuote. The following post is also very useful: https://stackoverflow.com/questions/24666515/how-do-i-make-an-attributed-string-using-swift. The problem now though is that the formatting i.e. font size, centre align has all changed. Do you have any suggestions on how to maintain original formatting? – Zenman C Apr 19 '19 at 03:57

1 Answers1

4

Thanks to @rmaddy for pointing me in the right direction. I went to the documentation here:

https://developer.apple.com/documentation/uikit/uitextview/1618626-attributedtext

And adjusted my code accordingly to:

self.text.attributedText = attributedQuote

I also found the following post really useful:

How do I make an attributed string using Swift?

One issue I still had is that when the above coding is applied, the original formatting - centre align, font size, constraints - for the textView is reset, so I readjusted them by adding in the appropriate attributes to the attributedString. See this article for more: https://www.hackingwithswift.com/articles/113/nsattributedstring-by-example

Zenman C
  • 1,653
  • 13
  • 21