Issue - Insert text works only for first time , the second time it appends to the end of the text

大城市里の小女人 提交于 2019-12-12 02:54:41

问题


URL I am adding text inside the uitextview using uipickerview.

Currently i am adding the text as below ( did select row method )

self.myTextView.text = [NSString stringWithFormat:@"%@ %@", self.myTextView.text,
            [myTierThreeData objectAtIndex:row]];

This works fine but i wanted to insert text where the cursor is so i did the below

-(void) pickerViewShown:(id)sender{
  myCursorPosition = [self.myTextView selectedRange];
}

When ever the pickerview is shown, taken the cursor position in the member variable.

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

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];

myCursorPosition = [self.myTextView selectedRange];
}

the above code works for the first time but when try to add next text , it appends the text at the end.

please let me know what is wrong with the above code


回答1:


Probably setting the text for the text field resets the cursor position to the end, so the only chance you have is to calculate the new cursor position yourself:

  • When starting the picker view, remember the original cursor position (like you do now) in myCursorPosition.
  • Every time you append text, add the text length to myCursorPosition, and use that value for inserting the next text.


来源:https://stackoverflow.com/questions/10380477/issue-insert-text-works-only-for-first-time-the-second-time-it-appends-to-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!