gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:30:18 29 4
gpt4 key购买 nike

在iOS应用的UITextView上打字时,如果文字超出了UITextView的宽度,UITextView会自动换行继续打字,但问题是当把文字拿出来的时候,还是只有一行文字。

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

但是当我从这个 textview 得到文本时

NSString* newtext = textview.text;

newtext 的值将是“AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOMMM”(都是一行),但我预计它将是“AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO\nMMM”(注意 '\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;
}

关于ios - 检测换行符以在 iOS 上的 UITextView 上自动输入换行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27513047/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com