1

I have an iOS project using Xcode 7 and Swift3. I have a UITextView that enables the user to save that text via NSUserDefaults into a String variable. However, if the user has a lot of text that includes paragraphs, when they save the text, it compiles it together to be one big long string of text, not recognizing the original paragraphs.

How do I have the string of text in essence recognize there are paragraphs and then make them into separate strings that are part of a [String]? Is this possible?

Example of text:

This is a complex task for me.

I don't know how to do this.

After the user names this text, which is two separate small paragraphs, it would save to NSUserDefaults as:

This is a complex task for me.  I don't know how to do this.

I know rather than save a String to NSUserDefaults I need to instead use a [String], but I still can't figure out how to take a UITextView and convert it's text into the string array, separating each paragraph into a separate String.

ChallengerGuy
  • 2,385
  • 6
  • 27
  • 43

2 Answers2

0

I looked at the reference in Apple's documents concerning paragraphs. I then took the advice and did the following:

// Assign the text to an NSString Variable
var newTextNS = instructions.text! as NSString

// Separate the text paragraphs into String Variables
var newArray = newTextNS.components(separatedBy: "\n")

I then had an array with all the different paragraphs as separate String variables.

Worked just as I needed it too.

ChallengerGuy
  • 2,385
  • 6
  • 27
  • 43
-2

Please check Apple's reference Words, Paragraphs, and Line Breaks

NSArray *arr = [myString componentsSeparatedByString:@"\n"];

or

NSString *string = /* assume this exists */;

NSRange range = NSMakeRange(0, string.length);

[string enumerateSubstringsInRange:range

                           options:NSStringEnumerationByParagraphs

                        usingBlock:^(NSString * _Nullable paragraph, NSRange paragraphRange, NSRange enclosingRange, BOOL * _Nonnull stop) {             // ... }];

Hope it helps.

user2071152
  • 1,161
  • 1
  • 11
  • 25