How to replace text in UITextView with selected range? - iphone

I want to replace the text in UITextView text in selected range. This is my question. Here i mention what i did? and what i want to do?. I have an UITextView and entered the below text in textview.
Ask question here, i have saved the range in of the text in textview. The text range is {17, 0}. I take the NSRange in -(void) textViewDidChange:(UITextView *)textView delegate.
Now i want to replace the text question with answer and i want to replace the text here with them. The UITextView.text look like this,Ask answer them` after replaced the texts.
How can i replace the texts with the selected ranges? Can you please help me? Thanks in advance.

Since iOS 7 there is the textStorage in the textView that inherits from NSMutableAttributedString so you can use those methods:
Objective-C
[self.textView.textStorage replaceCharactersInRange:withString:];
or
[self.textView.textStorage replaceCharactersInRange:withAttributedString:];
Swift
textView.textStorage.replaceCharacters(in: range, with: string)

Well... I'm not sure to understand correctly what you're trying to do, but if your goal is to change some characters in a selected range you can follow these steps:
Get your UITextView content and put it in a NSString:
NSString *textViewContent = textView.text;
Change the characters in the range you want:
NSString *newContent = [textViewContent stringByReplacingCharactersInRange:range withString:replacement];
Replace old content with new one:
textView.text = newContent;
Anyway if you just want to replace Ask question here with Ask answer them the fastest solution is just:
textView.text = #"Ask answer them";

Well solution from top of my head..
NSArray *Dividedstring = [[self.TextView.text] componentsSeparatedByString:#" question here "]; // this will divide the string into two parts ..one before question here and second after question here.
NSString * firstpart = [Dividedstring objectAtIndex:0];
NSString * secondpart = [Dividedstring objectAtIndex:0];
self.TextView.text = [NSString stringwithFormat:#"%# answer here %#",firstpart,secondpart];

Related

how to insert text at any cursor position in uitextview?

i want to implement Code by which i can start to insert text at any position of cursor in UITextView in iphone sdk
any idea?
thank you in advance..
i refereed this link: iPhone SDK: How to create a UITextView that inserts text where you tap?
But not Getting it.
Dan's answer is manually changing the text. It's not playing well with UITextView's UndoManager.
Actually it's very easy to insert text with UITextInput protocol API, which is supported by UITextView and UITextField.
[textView replaceRange:textView.selectedTextRange withText:insertingString];
Note: It's selectedTextRange in UITextInput protocol, rather than selectedRange
This is what I use with a custom keyboard, seems to work ok, there may be a cleaner approach, not sure.
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; // turn scrolling back on.
The simplest way (but it won't replace selected text) is to use the insertText: method:
[textView insertText:#"some text you want to insert"];
UITextView conforms to UITextInput which itself conforms to UIKeyInput.
Here is the Glorfindel's answer in Swift3. The text its inserting here it pulls out of the clipboard.
if let textRange = myTextView.selectedTextRange {
myTextView.replace(textRange, withText:UIPasteboard.general.string!)
}

Calculating enough text to fit within existing UILabel

I can't get some CoreText text wrapping code working for me; it's just too complicated. I'm going to try and go another route, which is to split my UILabel into two.
What I'm trying to achieve is to have my text appear to wrap around my fixed sized rectangular image. It'll always be the same dimensions.
So, when the UILabel next to the image fills up exactly, it'll create another UILabel below the image.
Now, how do I calculate the text in the first UILabel and have it fit nicely in the entire width of the UILabel, without being too short or cut off at the end?
Well, this ought to work to get the substring of the master string that will fit within the desired width:
//masterString is your long string that you're looking to break apart...
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[tempString componentsSeparatedByString:#" "]];
//Remove the last object, which is the last word in the string...
[tempArray removeLastObject];
//Recreate the tempString with the last word removed by piecing the objects/words back together...
tempString = #"";
for (int i=0; i < tempArray.count - 1; i++) {
tempString = [tempString stringByAppendingFormat:#"%# ", [tempArray objectAtIndex:i]];
}
//You must append the last object in tempArray without the space, or you will get an infinite loop...
tempString = [tempString stringByAppendingFormat:#"%#", [tempArray objectAtIndex:tempArray.count - 1]];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
Of course, this is assuming you want the separation to occur using word wrapping. If you don't mind words themselves being cut apart (i.e. character wrap) in order to fully take up the desired width, do this instead:
NSString *tempstring = masterString;
while (someLabel.bounds.size.width < [tempString sizeWithFont:someLabelLabel.font].width) {
tempString = [tempString substringToIndex:tempString.length - 1];
}
//Now do whatever you want with the tempString, which will fit in the width desired...
In order to get the remaining piece of the string left over, do this:
NSString *restOfString = [masterString substringFromIndex:tempString.length];
Hope this helps. I have to admit that I haven't properly tested this code yet, though I've done something similar in the past...
Try below link its will help you.
If you want to create a "link" on some custom text in your label, instead of using a WebView as #Fabian Kreiser suggested, you sould use my OHAttributedLabel class (you can find it this link)
See the sample code provided on my github repository: you can use my addCustomLink:inRange: method to add a link (with a customized URL) to a range of text (range that you could determine by iterating over every occurrences of the word "iPhone" in your text very easily). Then in the delegate method on OHAttributedLabel, you can catch when the link is tapped and act accordingly to do whatever you need.

Problem to write more than a line in a text view

i have a UITextView in which i have to write programmatically multiple lines. When i do this :
[textView setText:#"String number 1\n"];
[textView setText:#"String number 2\n"];
i get only : String number 2 as if it's writing the line over the other. I appreciate any suggestions :)
As the name suggests, setText: is a setter: it replaces the existing text.
That's quite like if you had an int val and you were doing:
val = 5;
val = 8;
Of course at the end val will be equal to 8 and the value 5 will be lost. Same thing here.
Instead, you need to create a string that contains all the lines, and affect directly to the textView:
[textView setText:#"Line1\nLine2\nLine3\n"];
If you need to do it incrementally, say you need to add text to existing text in the textView, first retrieve the existing text, append the new line, and set the new text back:
// get the existing text in the textView, e.g. "Line1\n", that you had set before
NSString* currentText = [textView text];
// append the new text to it
NSString* newText = [currentText stringByAppendingString:#"New Line\n"];
// affect the new text (combining the existing text + the added line) back to the textView
[textView setText:newText];
setText replace whole content of textView. You better to prepare result string and than set it by single setText method call.
for example:
NSString *resultString = [NSString stringWithFormat:#"%#%#", #"String 1\n", #"String 2\n"];
[textView setText:resultString];
you can append the strings :
mTextview.text = [mTextview.text stringByAppendingString:aStr];
According to How to create a multiline UITextfield?, UITextField is single-line only. Instead, use a UITextView.
In addition, as others have pointed out, if you call setText a second time, you'll overwrite the previous value. Instead, you should do something like this:
[textView setText:#"String number 1\nString number 2"]

How can I remove tab spacing from text for UILabel

I'm reading some text from a local xml file and displaying it in a UILabel. The text in the xml initially had tabbed spacing in it. I removed this tabbing manually in the editor but it's still showing up in the UILabel and it makes the text layout look very messy.
How can I resolve this?
Try with below
myLabel.text = [myText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet];
When you assign the text to your label you can do this:
myLabel.text = [textWithTabs stringByReplacingOccurrencesOfString:#"\t" withString:#""];
This will remove the tabs completely.
stringByTrimmingCharactersInSet:
Returns a new string made by removing
from both ends of the receiver
characters contained in a given
character set.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
NSString Class Reference

Contents of UITextField and UITextView to NSString

I have a UITextView and 2 UITextField set up. UITextView resigns first responder status when empty part of the screen is tapped, the same for the 2 UITextField, plus for these 2, the return key also resigns first responder status. All 3 are declared in interface.
I would like to get the contents of all of these to individual NSString and/or learn how to enter them directly into something like:
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?var1=%#&var2=%#&var3=%#", *content of UITextView*, *content of UITextField*, *content of UITextField*];
This is a very basic question, i know, but i'm pretty much a novice. If i learn how to do this i'll probably be able to pick up from there.
cheers
(edited)
UITextField and UITextView both have a text property that you can use to retrieve the string values. For example,
NSString *string = [NSString stringWithFormat:#"%#, %#", textField.text, textView.text];
Keep in mind you'll probably want to examine the strings to make sure they're not empty or contain invalid characters before putting them into a URL.
The accepted answer is good, I just wanted to add the following for an expanded look at grabbing text in iOS.
See the textInRange: aspect of the below code that I devised to use one function to determine the text whether it's a UITextField, UITextView or any other class that complies with the UITextInput protocol.
//handle text container object length whether it's a UITextField, UITextView et al
NSUInteger LengthOfStringInTextInput(NSObject<UITextInput> *textContainer)
{
UITextPosition *beginningOfDocument = [textContainer beginningOfDocument];
UITextPosition *endOfDocument = [textContainer endOfDocument];
UITextRange *fullTextRange = [textContainer textRangeFromPosition:beginningOfDocument
toPosition:endOfDocument];
return [textContainer textInRange:fullTextRange].length;
}
By changing the return type to NSString and removing .length you could have the functionality of the text property on any class.