Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build an Interactive Story App with Swift Creating the User Interface Programmatically Attributed Strings

Wing Sun Cheung
Wing Sun Cheung
4,933 Points

The store property of attributedText is NOT a type NSMutableAttributedString

Hi team,

I am really confused here. Inside of UILabel class, there is a property called:

var attributedText: NSAttributedString?

In the video, Pasan did this:

let attributedString = NSMutableAttributedString(string: page.story.text)
storyLabel.attributedText = attributedString

How is this possible? what I am confused about is var attributedText accepts only NSAttributedString, but somehow it also accepts NSMutableAttributedString?

Is it because since NSMutableAttributedString inherits from NSAttributedString, that makes NSMutableAttributedString equal to NSAttributedString?

thanks

2 Answers

Lone Nielsen
Lone Nielsen
13,764 Points

This here is the right answer

attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))

almost nailed it, missing dot before the Key, or at least for Xcode 10.2.1 this is the right solution for the attributedString:

attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))

Ashwin Iyer
Ashwin Iyer
11,684 Points

Hey so if you go back to around 1:40 in the video, he explains it better. But essentially, in objective C you need to use mutable types to be able to modify the objects. If we were to simply use NSAttributedString when we were changing the attributes, we would not be allowed to since the type is non-mutable.