UITextField full solution for iOS

Source: Internet
Author: User
Tags uicontrol

UITextField full solution for iOS
Here we share it with you in the form of code. Refer to the blog on IOS-TextField. Here, CAT and CAT mainly use markdown to optimize the directory structure for ease of reading.
Initialize textfield and set the position and size

  UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)];
Set the border style. The border style is displayed only when it is set.
  text.borderStyle = UITextBorderStyleRoundedRect;  typedef enum {    UITextBorderStyleNone,     UITextBorderStyleLine,    UITextBorderStyleBezel,    UITextBorderStyleRoundedRect    } UITextBorderStyle;
Set the background color of the input box to white. If a custom background image border is used, it is ignored.
 text.backgroundColor = [UIColor whiteColor];
Set background
  text.background = [UIImage imageNamed:@"dd.png"];
Set background
  text.disabledBackground = [UIImage imageNamed:@"cc.png"];
When there is no content in the input box, the watermark prompts that the content is password
  text.placeholder = @"password";

// Set the font style and size of the input box.

text.font = [UIFont fontWithName:@"Arial" size:20.0f];
Set Font color
  text.textColor = [UIColor redColor];
Whether there is a cross in the input box. When is it displayed? It is used to delete the content in the input box at a time.
Text. clearButtonMode = UITextFieldViewModeAlways; typedef enum {UITextFieldViewModeNever. If the volume is not repeated, the volume is displayed during editing, and UITextFieldViewModeAlways appears all the time except for editing;
Text in the input box
Text. text = @ "text in the input box at the beginning ";
Each character is entered as a point term and a password.
  text.secureTextEntry = YES;
Error Correction?
Text. autocorrectionType = regular; typedef enum {UITextAutocorrectionTypeDefault, UITextAutocorrectionTypeNo by default. UITextAutocorrectionTypeYes, automatic error correction} UITextAutocorrectionType;
Click Edit again to clear it.
  text.clearsOnBeginEditing = YES; 
Content alignment
  text.textAlignment = UITextAlignmentLeft;
The vertical alignment of the content. UITextField inherits from UIControl. This class has a contentverticalignment attribute.
  text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
When the value is set to YES, the text will be automatically reduced to accommodate the size of the text window. By default, the original size is kept, and the long text will be rolled over.
  textFied.adjustsFontSizeToFitWidth = YES;
Sets the minimum font size for auto-scaling.
  text.minimumFontSize = 20;
Set the keyboard Style
Text. keyboardType = UIKeyboardTypeNumberPad; typedef enum {UIKeyboardTypeDefault, default keyboard, all characters supported, ASCII default keyboard, standard phone keyboard, + * # character UIKeyboardTypeURL, URL keyboard, supported. the com button only supports the URL character UIKeyboardTypeNumberPad, The UIKeyboardTypePhonePad, the telephone keyboard, and the telephone keyboard. You can also enter the name UIKeyboardTypeEmailAddress, the numeric keypad has numbers and decimal points UIKeyboardTypeTwitter. The optimized keypad facilitates the input of @ and # characters UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable,} UIKeyboardType;
Whether the first letter is capitalized
Text. autocapitalizationType = strong; typedef enum {UITextAutocapitalizationTypeNone, not automatically capitalized UITextAutocapitalizationTypeWords, the first letter of a word in upper case, and all letters in upper case} UITextAutocapitalizationType;
What key does the return key become?
Text. returnKeyType = UIReturnKeyDone; typedef enum {UIReturnKeyDefault, UIReturnKeyNext, UIReturnKeyNext, UIReturnKeyRoute, UIReturnKeySearch, UIReturnKeySend, UIReturnKeySend, and UIReturnKeyYahoo, UIReturnKeyYahoo, UIReturnKeyEmergencyCall, and emergency call.} UIReturnKeyType;
Keyboard appearance
TextView. keyboardAppearance = UIKeyboardAppearanceDefault; typedef enum {UIKeyboardAppearanceDefault, default appearance, light gray UIKeyboardAppearanceAlert, dark gray graphite} UIReturnKeyType;
Set proxy for protocol implementation
  text.delegate = self;
Add textfield to view
  [self.window addSubview:text];
Add the image on the rightmost side as shown in the following code.
    UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];    text.rightView=image;    text.rightViewMode = UITextFieldViewModeAlways; typedef enum {    UITextFieldViewModeNever,    UITextFieldViewModeWhileEditing,    UITextFieldViewModeUnlessEditing,    UITextFieldViewModeAlways} UITextFieldViewMode;
Press the return key and press the keyboard to close down.

The becomeFirstResponder class adopts the UITextFieldDelegate protocol.

Text. delegate = self; I declare that the proxy of text is me. I will implement the method of receiving the keyboard down in UITextFieldDelegate. So we need to use the UITextFieldDelegate protocol.

-(BOOL) textFieldShouldReturn :( UITextField *) textField {[text resignFirstResponder]; // It mainly refers to the call where the [receiver resignFirstResponder] can push the keyboard corresponding to the receiver down to return YES ;}
Rewrite painting Behavior

In addition to the style options of the UITextField object, you can also customize the UITextField object and add many different rewriting methods for it to change the display behavior of text fields. These methods return a CGRect structure and define the boundary range of each part in the text field. You can override the following methods.

-TextRectForBounds: // rewrite to reset the text area-drawTextInRect: // modify the painted text attributes. during rewriting, you can call super to draw based on the default graphic attribute. If you completely rewrite the rendering function, you do not need to call super. -placeholderRectForBounds: // override to reset the placeholder area-drawPlaceholderInRect: // override to change the drawing placeholder attribute. during rewriting, you can call super to draw based on the default graphic attribute. If you completely rewrite the rendering function, you do not need to call super. -borderRectForBounds: // rewrite to reset the Edge Area-editingRectForBounds: // rewrite to reset the editing area-clearButtonRectForBounds: // rewrite to reset the clearButton position, changing the size may cause distortion of the button image-leftViewRectForBounds:-rightViewRectForBounds:

Delegate Method

-(BOOL) textFieldShouldBeginEditing :( UITextField *) textField {// return a BOOL value and specify whether to edit the return YES field in sequence;}-(void) textFieldDidBeginEditing :( UITextField *) textField {// triggered when editing starts. The text field will become first responder}-(BOOL) textFieldShouldEndEditing :( UITextField *) textField {// return BOOL value, specifies whether to allow end-editing of text fields. When the end of editing, the text field will give way to the first responder // to prevent text fields from disappearing when the end of editing, NO can be returned // This is useful for some programs whose text fields must always be active, such as instant message return NO;}-(BOOL) textFie Ld :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string {// when the user uses the automatic correction function to change the input text to the recommended text, this method is called. // This is especially useful for applications that want to add revocation options. // you can trace the last modification made in the field, or log all edits for auditing purposes. // To prevent text changes, NO can be returned. // The parameter of this method has a nsange object, indicating the location of the changed text. The recommended text also returns YES ;} -(BOOL) textFieldShouldClear :( UITextField *) textField {// return a BOOL value to indicate whether to allow content to be cleared based on user requests. // you can set the condition to allow content to be cleared. return YES;}-(BOOL) textFieldShouldReturn :( UITextField *) textField {// return a BOOL value indicating whether to allow end editing when the Enter key is pressed // If the resignFirstResponder method is allowed, this will lead to end editing, the keyboard will be collapsed [textField resignFirstResponder]; // check the meaning of the resign to understand this method. return YES ;}
Notification

UITextField is derived from UIControl, so the notification system in the UIControl class can also be used in text fields. In addition to standard events of the UIControl class, you can also use the following UITextField-specific events

UITextFieldTextDidBeginEditingNotificationUITextFieldTextDidChangeNotificationUITextFieldTextDidEndEditingNotification

Triggered when the text field exits the editing mode. The object Property of the notification stores the final text.

Because text fields use the keyboard to input text, action notifications are also sent when the following events occur.

UIKeyboardWillShowNotification // send UIKeyboardDidShowNotification before display on the keyboard // send UIKeyboardWillHideNotification after display on the keyboard // send UIKeyboardDidHideNotification before hiding the keyboard // send it after hiding the keyboard

1. Text: Set the default Text of the Text box.
2. Placeholder: displays the gray text box, prompting you what to enter in this text box. When data is entered in this text box, the gray words used for the prompt will automatically disappear.
3. Background:
4. Disabled: If this option is selected, you cannot change the text box.
5. Next, there are three buttons for setting alignment.
6. Border Style: select the Border Style.
7. Clear Button: this is a drop-down menu. You can select when the Clear Button appears. The Clear Button is a small X on the right of the text box. You can select the following options:
7.1 Never appears: Never appears
7.2 Appears while editing: displayed during editing
7.3 Appears unless editing:
7.4 Is always visible: always visible
8. Clear when editing begins: If this option is selected, the previous content in the text box will be cleared when you start to edit the text box. For example, if you enter "What" in text box A, then edit text box B. If you come back to edit text box A, "What" is immediately cleared.
9. Text Color: Set the Text Color in the Text box.
10. Font: Set the Font and Font size of the text.
11. Min Font Size: Set the smallest Font that can be displayed in the text box (but I feel useless)
12. Adjust To Fit: Specifies whether To reduce the size of the text box by an hour. Select it to make all the text visible, even if the text is too long. However, this option should be used with Min Font Size, and the text will be reduced, and it will not be smaller than the set Min Font Size.
The following section is used to set how the keyboard is displayed.
13. Captitalization: Set to uppercase. The drop-down menu has four options:
13.1 None: Do not set upper case
13.2 Words: the first letter of each word is capitalized. The Words here refer to strings separated by spaces.
13.3 Sentances: the first letter of each sentence in uppercase. The sentence here is a string separated by periods and spaces.
13.4 All Characters: uppercase letters
14. Correction: check spelling. The default value is YES.
15. Keyboard: select the Keyboard type, such as full numbers, letters, and numbers.
16. Appearance:
17. Return Key: select the Return Key. You can select Search, Return, and Done.
18. Auto-enable Return Key: If this option is selected, the Return Key is valid only when at least one character is entered in the text box.
19. Secure: when your text box is used as the password input box, you can select this option. The character is displayed as an asterisk.

1. Alignment Horizontal Alignment
2. Alignment Vertical Alignment
3. Return whether the input box of a BOOL value is Selected (Selected) Enabled (available) Highlighted (Highlighted)

Only specific characters can be entered.
(BOOL) textField :( UITextField *) textField parameters :( nsange) range replacementString :( NSString *) string {NSCharacterSet * cs; cs = [[NSCharacterSet parameters: NUMBERS] invertedSet]; NSString * filtered = [[string componentsSeparatedByCharactersInSet: cs] componentsJoinedByString: @ "]; // separates arrays by cs, array splits the string BOOL canChange = [string isEqualToString: filtered]; r @ "" Eturn canChange;} The NUMBERS above is a macro, which can be defined at the top of the file: # define NUMBERS @ "0123456789 \ n" (This indicates that NUMBERS and line breaks can be entered, please note this \ n. If you do not write this, The Done button will not trigger. If you use it in the SearchBar, it will not trigger the Search event, because you will not allow the input \ n by yourself, I found it only in the project .) Therefore, if you want to restrict the input of English letters and numbers, you can define this as: # define kAlphaNum @ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ″. Of course, you can also make a prompt before the return method, such as prompting users to enter only numbers. If you need it. Only characters of a certain length can be entered-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string; {// string is the character textField that is input at this time. The input box that is being input at this time returns YES, which can change the value of the input box. if ([string is1_tostring: @ "\ n"]) // You Can Change {return YES;} NSString * toBeString = [textField. text stringByReplacingCharactersInRange: range withString: string]; // obtain the content of the input box if (self. myTextField = textField) // specifies the input box {if ([toBeString length]> 20) that we want to specify when determining whether the input box is used {// if the input box contains more than 20 content, a warning textField is displayed. text = [toBeString substringToIndex: 20]; UIAlertView * alert = [[[UIAlertView alloc] initWithTitle: nil message: @ "the maximum number of words cannot be entered" delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil] autorelles]; [alert show]; return NO ;}} return YES ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.