在光标所在的位置插入字符串

时间:2012-04-30 06:20:29

标签: iphone ios ios4

我想在光标当前插入文本,所以我有以下代码

    NSString *contentsToAdd = [myData objectAtIndex:row];
    NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[self.myTextView text]];
    // add content where the cursor was 
   [tfContent insertString:contentsToAdd atIndex:myCursorPosition.location];
  [self.myTextView setText:tfContent];
   [tfContent release];

    This works as below
    Hi
    HiFriend

实际上我想在附加文字之前和之后留下一个空格(嗨朋友)。

那我该怎么做呢。 帮助我,干杯

2 个答案:

答案 0 :(得分:0)

尝试类似:

NSString *contentsToAdd = [myData objectAtIndex:row];
NSMutableString *tfContent = [[NSMutableString alloc] initWithString:[self.myTextView text]];
// add content where the cursor was 
NSString *contentsToAddPadded = [NSString stringWithFormat:@" %@ ", contentsToAdd];
[tfContent insertString:contentsToAddPadded atIndex:myCursorPosition.location];
[self.myTextView setText:tfContent];
[tfContent release];

答案 1 :(得分:0)

尝试这样的事情:

NSString *beginning = [self.myTextView.text substringToIndex:currentRange.location];
NSString *ending = [self.myTextView.text substringFromIndex:currentRange.location];
self.myTextView.text = [NSString stringWithFormat:@"%@% @% @",beginning, contentsToAdd, ending, nil];
相关问题