Contents of UITextField and UITextView to NSString - iphone

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.

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!)
}

How to replace text in UITextView with selected range?

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

iPhone : Textfields and NSNumberFormatter

I am making an app with multiple textfields. I would like when the user enters a number in the textfield, to automatically add the percent symbol when editing ends. Right now, the only way i know how to do that is to convert the text value to float, then use NSNumberFormatterPercentStyle and then send back the value. I guess that there should be a simpler and faster way to do that for multiple textfileds. Does anyone know?
You could use the UITextFieldDelegate's textFieldDidEndEditing: method.
For example:
- (void)textFieldDidEndEditing:(UITextField *)textField {
NSString *oldTextFieldValue = textField.text;
textField.text = [NSString stringWithFormat:#"%# %%",oldTextFieldValue];
}
Note the double "%" in the stringWithFormat: method: this is because a single % on its own is a "format specifier" and will not be taken into account and xcode will give you a warning, so you need to protect it with a second %.

Newbie to iPhone SDK. How can I insert text into a UILabel without 'setText'...?

Okay, so I have a basic application and I built a custom numeric keyboard using some buttons. I have a button, for example 1, and a UILabel above. I got it to where when you click the button 1, it sets the text of the label to 1. Pretty simple stuff. But I need to add multiple characters and it's not letting me do so. Something like addText or insertText but addText isn't even a Cocoa method and insertText isn't what I'm looking for. Any help? Sorry for the newbie question. Thanks!
If what you’re looking for is a way to append a character to the end of the label’s string, do something like this:
[myLabel setText:[[myLabel text] stringByAppendingString:#"1"]];
A UILabel's text property is an NSString. You should look over the NSString documentation to see what all is possible. The methods stringByAppendingString, stringByAppendingFormat, and stringWithFormat look like they might be useful for your problem.
#Jeff Kelley answered your question about appending text to a UILabel. With regards to your follow-up comment about the price:
If the user is entering numeric values into a UITextField, the delegate should respond to the -textField:shouldChangeCharactersInRange:replacementString: method. An example of what you might do is:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
[fmt setGeneratesDecimalNumbers:YES];
NSDecimalNumber *newCentValue = [[fmt numberFromString:string] decimalNumberByMultiplyingByPowerOf10:-2];
// "price" is an instance, global, static, whatever.. NSDecimalNumber object
NSDecimalNumber *newPrice = [[price decimalNumberByMultiplyingByPowerOf10:1] decimalNumberByAdding:newCentValue];
NSString *labelText = [fmt stringFromNumber:newPrice];
// do something with new label
}
Note that this method does not deal with the user wanting to remove a digit, etc.

UITextView.text property doesn't update first time, and then clips or doesn't display when it does

I'm trying to get the contents from a dictionary into a UITextView. The dictionary contains molecular masses paired with percentages, for example:
24 -> 98
25 -> 1.9
26 -> 0.1
I have an NSArray containing the keys from the dictionary, sorted in ascending order. So, here is my code to generate the string to set as the textField.text property:
-(void)detailIsotopes:(NSMutableDictionary *)isotopes withOrder:(NSMutableArray *)order{
NSMutableString *detailString = [[NSMutableString alloc] init];
for (NSNumber *mass in order){
[detailString appendString:[NSString stringWithFormat:#"%d: %f\n", [mass integerValue], [[isotopes valueForKey:[NSString stringWithFormat:#"%#", mass]] floatValue]]];
}
NSLog(#"%#", detailString);
textField.text = detailString;
[detailString release];
}
This should create a string looking like this:
24: 89
25: 1.9
26: 0.1
For some reason, this method never does anything the first time it runs. I see the NSLog output, which outputs the correct string. However, the contents of the UITextView don't change: they stay as 'Lorem ipsum dolor sit amet...' from Interface Builder. If I run the method again, it works, sort of.
The UITextView displays some of the text, and then just cuts off half way through a line, leaving only the tops of the characters. If I delete the contents above the half line, the other lines pull up from under the divide: the contents are there, they just stop being shown, if you understand what I mean. This appears to go away if I enable paging in the view. If I do that, then the line isn't truncated, but the UITextView just stops showing any content after some point, although the scroll bar indicates that there is more to go (which there is).
The view containing the UITextView is not visible when the contents is set, if that makes a difference. A separate view controller generates the NSMutableDictionary and NSMutableArray and sends them to its delegate, which then sends them to the view which should display the UITextField and has the detailIsotopes: withOrder: method. The two can be swapped between with an info button.
Does anyone understand why these things are happening?
Thanks for any advice you can give!
First of all, I don't think you need to allocate and release your NSMutableString here. Simply initialize one using [NSMutableString string] which creates an empty string you can modify and don't need to explicitly release.
Second thing, you seem to store masses in NSStrings in your NSDictionnary, why do you use their integerValue method for stringWithFormat (with %d modifier), instead of using them as is? (the stringWithFormat modifier for NSStrings is %#)
Also, you talk about a UITextView at start, then about a UITextField, are you sure you did not make a mistake somewhere? I guess the receiving object for your formatted NSString should rather be the UITextView (if you have both a textField and textView).
If it's not about this, maybe you are calling detailIsotopes too early and the textView it's created yet. Try to NSLog its address and see if it's nil the first time. It could be the case if you use Interface Builder and your UITextField is an ib outlet. If you do, then you could store your dictionary and array in the viewController, and set the textField in the viewController's viewDidLoad method. Or call detailIsotopes after you've displayed the view, I guess that's up to you.
About the truncated text, I think that's because UITextView doesn't resize itself automatically, so it keeps the height you originally set. What I usually do is this:
CGRect frame = textView.frame;
frame.size.height = textView.contentSize; // you can adjust this to leave some space at the end
textView.frame = frame;
This will set the textView height to the content (the text) height.
Also note that if your textView is supposed to display the whole text, you can set its scrollingEnabled property to FALSE so it never allows scrolling.
Hope that helps.