0
NSString * myText = @"This is my really long text view";
NSUInterger textLenght = [myText length]; //NSLog 32

如何在所选长度位置插入任何文本。例如,长度为 10?

我试过这个,但它不起作用!

NSRange textRange = [myText rangeOfComposedCharacterSequenceAtIndex:10];
[myText stringByReplacingCharactersInRange:textRange withString:@"NEW"];
4

1 回答 1

3

分配它:

myText=[myText stringByReplacingCharactersInRange:textRange withString:@"NEW"];

一个 NSString 是不可变的,你不能改变它的字符,这就是为什么 stringByReplacingCharactersInRange 不会重新排列字符,而是返回另一个从头开始构建的字符串。

考虑使用NSMutableString

NSMutableString * myText = [[NSMutableString alloc]initWithString: @"This is my really long text view"];
NSRange textRange = [myText rangeOfComposedCharacterSequenceAtIndex:10];
[myText replaceCharactersInRange: textRange withString:@"NEW"];
于 2012-12-27T16:13:26.920 回答