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.

链接地址: http://www.djcxy.com/p/44302.html

上一篇: UITableViewCell辞职FirstResponder

下一篇: UITextField和UITextView的内容到NSString