AFB
AFB

Reputation: 560

iOS - appending string before and after the word

I want to add a string in the highlighted area in the textview, I mean by the highlighted area, where the blue line is located.

So once the user click on the button it adds a string where the "blue line" is located

I used stringByAppendingString but it adds the string after the word exists only

Upvotes: 0

Views: 585

Answers (3)

madLokesh
madLokesh

Reputation: 1878

Even though its not clear what you are trying to achieve, it seems that you want the user to start editing the textfield from the position where text starts. In that case , you can refer following:

Hint 1

Set your view controller (or some other appropriate object) as the text field's delegate and implement the textFieldDidBeginEditing: method like this:

- (void)textFieldDidBeginEditing:(UITextField *)textField
 {
    UITextPosition *beginning = [textField beginningOfDocument];
    [textField setSelectedTextRange:[textField textRangeFromPosition:beginning
                                                      toPosition:beginning]];
 }

Note that setSelectedTextRange: is a protocol method of UITextInput (which UITextField implements), so you won't find it directly in the UITextField documentation.

Hint 2

self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];

Hint 3

finding-the-cursor-position-in-a-uitextfield/

Upvotes: 1

Pandey_Laxman
Pandey_Laxman

Reputation: 3908

NSRange range = myTextView.selectedRange;  
NSString * firstHalfString = [myTextView.text substringToIndex:range.location];  
NSString * secondHalfString = [myTextView.text substringFromIndex: range.location];  
myTextView.scrollEnabled = NO;  // turn off scrolling  

NSString * insertingString = [NSString stringWithFormat:@"your string value here"];

myTextView.text = [NSString stringWithFormat: @"%@%@%@",  
             firstHalfString,  
             insertingString,  
             secondHalfString];  
range.location += [insertingString length];  
 myTextView.selectedRange = range;  
 myTextView.scrollEnabled = YES; 

Upvotes: 3

Wain
Wain

Reputation: 119031

You need to use the selectedRange to find out where the text cursor is. Then use replaceCharactersInRange:withString: or insertString:atIndex: to insert the new text into the original text. Then update the text into the view.

Upvotes: 3

Related Questions