Sco*_*ran 1 newline uitextview ios
在iOS应用程序的UITextView上输入时,如果文本超出了UITextView的宽度,UITextView将自动进入新行并继续输入,但问题是当文本输出时,它仍然只是单行文本.

但是当我从这个textview获取文本时
NSString* newtext = textview.text;
Run Code Online (Sandbox Code Playgroud)
newtext的值将是"AAAAAAAAAAAAAAAAAAAAAAAAAAAAOMMM"(所有都是单行),但我预计它将是"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOMA"(注意'\n'字符通知新行)
有没有办法做到这一点
在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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2484 次 |
| 最近记录: |