在iOS上的UITextView上检测自动输入新行文本的换行符

时间:2014-12-16 20:09:54

标签: ios uitextview newline

在iOS应用上的UITextView上输入时,如果文本超出UITextView的宽度,UITextView将自动进入新行并继续输入,但问题是当文本输出时,它仍然只是一行文本。

The 'M' character is automatically broken into new line after 'O' character

但是当我从这个文本视图中获取文本时

NSString* newtext = textview.text;

newtext的价值将是" AAAAAAAAAAAAAAAAAAAAAAAAAAAAOMMM" (所有都是单线)但我预计它将是" AAAAAAAAAAAAAAAAAAAAAAAAAAAAAO \ nMMM" (注意' \ n'字符通知新行)

有没有办法做到这一点

1 个答案:

答案 0 :(得分:7)

UITextView一旦文本到达行尾,就不会自动输入换行符 - 它只是换行换行符。但是如果你想要一个包含换行符的UITextView文本的字符串表示来指示各种换行符,请尝试这样:

// This method takes in the `UITextView` and returns the string
// representation which includes the newline characters
- (NSString*)textViewWithNewLines:(UITextView*)textView {

    // Create a variable to store the new string
    NSString *stringWithNewlines = @"";

    // Get the height of line one and store it in
    // a variable representing the height of the current
    // line
    int currentLineHeight = textView.font.lineHeight;

    // Go through the text view character by character
    for (int i = 0 ; i < textView.text.length ; i ++) {

        // Place the cursor at the current character
        textView.selectedRange = NSMakeRange(i, 0);

        // And use the cursor position to help calculate
        // the current line height within the text view
        CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin;

        // If the y value of the cursor is greater than
        // the currentLineHeight, we've moved onto the next line
        if (cursorPosition.y > currentLineHeight) {

            // Increment the currentLineHeight such that it's
            // set to the height of the next line
            currentLineHeight += textView.font.lineHeight;

            // If there isn't a user inputted newline already,
            // add a newline character to reflect the new line.
            if (textView.text.length > i - 1 &&
                [textView.text characterAtIndex:i-1] != '\n') {
                stringWithNewlines = [stringWithNewlines stringByAppendingString:@"\n"];
            }

            // Then add the character to the stringWithNewlines variable
            stringWithNewlines = [stringWithNewlines stringByAppendingString:[textView.text substringWithRange:NSMakeRange(i, 1)]];
        } else {

            // If the character is still on the "current line" simply
            // add the character to the stringWithNewlines variable
            stringWithNewlines = [stringWithNewlines stringByAppendingString:[textView.text substringWithRange:NSMakeRange(i, 1)]];
        }
    }

    // Return the string representation of the text view
    // now containing the newlines
    return stringWithNewlines;
}