为新行文本输入 UITextView iOS 上自动检测新行字符

标签: UITextView ios
发布时间: 2015/6/27 7:17:53
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

如果文本是 UITextView 宽度以外,UITextView 将自动输入新行并继续键入,但问题是,在 UITextView iOS 应用程序,在输入的时候什么时候出来,它的仍然只是一个单行文本的文本。

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

但是,当我从这个 textview 获取文本

NSString* newtext = textview.text;

Newtext 的值将为"AAAAAAAAAAAAAAAAAAAAAAAAAAAAOMMM"(全部是一线),但我要它将"AAAAAAAAAAAAAAAAAAAAAAAAAAAAO\nMMM"(公告通知新行的 \n 字符)

有没有办法做到这一点

解决方法 1:

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;
}
官方微信
官方QQ群
31647020