Is NSAttributedString available before iOS 6?

2019-02-16 17:10发布

问题:

I have found conflicting information on the availability of NSAttributedString for iOS versions before 6. It is something that would be really useful if it is somewhat backwards compatible.

Here it says it is available as of iOS 4: Why No NSAttributedString on the iPhone?

On the Apple website it says iOS 6 and later: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html

I tried implementing it in my code like so:

NSAttributedString *commentString = [[NSAttributedString alloc] initWithString:@"I really love raisins" attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];

It works in iOS 6 but not when I try to run it in iOS 5 or iOS 5.1. I haven't tested earlier versions.

Am I just trying to use features not included in older versions?

回答1:

It has been around since iOS3.2. However the ability to use them within certain UI controls such as UILabel, UIButton, UITextView, etc is only available since iOS6. You can still use them using CoreText for < 6.0.



回答2:

NSAttributeString and the initWithString:attributes: method have been around since iOS 3.2 according to the iOS reference docs. Some method of NSAttributedString were added in iOS 4.0. All of the methods added as a UIKit category were added in iOS 6.0.

The problem with this line:

NSAttributedString *commentString = [[NSAttributedString alloc] initWithString:@"I really love raisins" attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];

is that the NSForegroundColorAttributeName constant wasn't added until iOS 6.0.

So while NSAttributedString has been around for a while, all of the useful stuff wasn't added until 6.0.



回答3:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html

In iOS 6 and later you can use attributed strings to display formatted text in text views, text fields, and some other controls

It is only IOS6 afaik. The class was available prior to IOS6, but the functaionality was not available. So your final assumption is correct :)