我想这是一个有点尴尬的问题,所以让我用一个例子来重新表述一下:
我有一个 UITextView,它仅限于一定数量的字符。定期使用 - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText
检查。一旦文本大于阈值(在插图中为 8 个字符),应用程序将更改到下一个 textView 并将输入的下一个字符(在本例中为 p)复制到新的 UITextView。然后用户可以输入单词的其余部分(在本例中为 py)。
我不想将单词拆分为两个 UITextView,而是希望在下一个 UITextView 中包含整个单词“happy”。换句话说,我需要将字符串 1 中的“hap”复制到字符串 2 的开头,然后从字符串 1 中删除“hap”。
我想出了这段代码,它检查字符串 1 中的空格,并将空格后的所有内容复制到字符串 2 中。但它不起作用:
NSLog(@"text of current string: %@", aTextView.text); // e.g. "I am hap"
NSLog(@"chars in aTextView.text: %i", aTextView.text.length); // e.g. 8 chars
NSLog(@"text for next string: %@ ", aText); // e.g. "py"
NSString *aTextModified = aText;
for (int i = aTextView.text.length; i > 0; i--) {
NSLog(@"I currently check: '@%'", [aTextView.text characterAtIndex:i]);
if ([[aTextView.text characterAtIndex:i] isEqualToString:@" "]) {
// job done
} else {
NSLog(@"I add %@ infront of %@", [aTextView.text characterAtIndex:i], aText);
aTextModified = [NSString stringWithFormat:@"%@%@", [aTextView.text characterAtIndex:i], aText];
NSLog(@"I delete %@ as I have put it into the next string...", [aTextView.text characterAtIndex:i]);
[aTextView.text characterAtIndex:i] = @"";
}
}
XCode 向我发出警告:if ([[aTextView.text characterAtIndex:i] isEqualToString:@""])
行的接收器类型“unichar”无效。我想我没有使用characterAtIndex,对吧?我是否不允许将此应用于 UITextView 中的文本(应该是 UIString)?
此外,我在最后一行收到错误“LValue required as left opperand of assignment”[aTextView.text characterAtIndex:i] = @"";
再次,我想我不知道真正理解如何访问 UITextView 中的字符并修改它。
如果有任何有关如何正确执行此操作的建议,以及是否有更简单的方法来实现我想要做的事情,我将非常感激。
最佳答案
几件事
NSLog(@"I currently check: '@%'", [aTextView.text characterAtIndex:i]);
您在这里得到一个 C
字符,因此您应该使用 %c
来代替。
[[aTextView.text characterAtIndex:i] isEqualToString:@" "]
同样,您在这里所做的是向 C
字符发送一条消息,这是不正确的。您可以将其更改为 [aTextView.text characterAtIndex:i] == ""
以正确执行此操作。
[aTextView.text characterAtIndex:i] = @"";
text
被定义为不可变字符串。你不能这样改变它。您必须声明一个可变字符串并复制 text
的内容。修改可变字符串后,您可以将其设置为text
。
这也会给你最后一句话。
NSScanner *wordsScanner = [NSScanner scannerWithString:@"I am happy however I want the last word and it's positions !!!!"];
NSString *theLastWord;
while (![wordsScanner isAtEnd]) {
[wordsScanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:&theLastWord];
}
// theLastWord has the value.
编辑
NSString *text = aTextView.text;
int index = text.length - 1;
while ([text characterAtIndex:index] != " ") {
index--;
}
NSString stringToBeMoved = [text substringFromIndex:index];
aTextView.text = [text substringToIndex:(index+1)];
关于iphone - 如何避免将一个单词拆分为两个 UITextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6069238/