将文本从 UITextView 添加到数组?

Add text from UITextView to array?

如何将 UITextView 中的每一行文本添加到数组中?我想这样做是为了允许用户在 TextView 中创建一个列表,并在以后从中提取随机条目。我想我需要解析 TextView 中的文本并按行排序,但我不确定如何实现它。

您需要在每个换行符处拆分 UITextView。这可以通过以下代码完成:

    let values = split(textView.text.characters) { [=10=] == "\n" } .map { String([=10=]) }

如有必要,您还可以使用sorted()函数对字符串数组进行排序:

    .sorted { [=11=] <  }

实施

let values = textView.text.componentsSeparatedByString("\n")

例子

var textViewText = "jkl \n def \n ghi \n abc"
let values = textViewText.componentsSeparatedByString("\n") // ["jkl ", " def ", " ghi ", " abc"]

如果你想排序,你可以这样做:

let sortedValues = values.sort { [=12=] <  } // [" abc", " def ", " ghi ", "jkl "]
NSMutableArray *array

array=[[NSMutableArray alloc]init];

- (IBAction)save:(id)sender
{ 
    NSString *string =UITextField.text;
    [array addObject:string];
}