Full solution of iOS UITextField, iOSUITextField

Source: Internet
Author: User
Tags uicontrol

Full solution of iOS UITextField, iOSUITextField

// 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 the background

Text. background = [UIImage imageNamed: @ "dd.png"];

 

// Set the background

Text. disabledBackground = [UIImage imageNamed: @ "cc.png"];

 

// When no content exists in the input box, the prompt "password" is displayed.

Text. placeholder = @ "password ";

 

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

Text. font = [UIFont fontWithName: @ "Arial" size: 20366f];

 

// Set the 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

UITextFieldViewModeWhileEditing, displayed during editing

UITextFieldViewModeUnlessEditing

UITextFieldViewModeAlways always appears

} UITextFieldViewMode;

 

// Some text from the beginning in the input box

Text. text = @ "text in the input box at the beginning ";

 

// Each character is entered as a point term and password

Text. secureTextEntry = YES;

 

// Whether to correct the error

Text. autocorrectionType = UITextAutocorrectionTypeNo;

 

Typedef enum {

UITextAutocorrectionTypeDefault, default

UITextAutocorrectionTypeNo, which does not automatically correct errors

UITextAutocorrectionTypeYes, Automatic Error Correction

} UITextAutocorrectionType;

 

// Clear after editing again

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 = uicontrolcontentverticalignmentcenter;

 

// When it is set to YES, the text will be automatically reduced to adapt to the text window size. By default, the original size is kept, and the long text is rolled.

TextFied. adjustsFontSizeToFitWidth = YES;

 

// Set the minimum font size for auto scaling down.

Text. minimumFontSize = 20;

 

// Set the keyboard Style

Text. keyboardType = UIKeyboardTypeNumberPad;

 

Typedef enum {

UIKeyboardTypeDefault, default keyboard, supports all characters

UIKeyboardTypeASCIICapable, supporting the default ASCII keyboard

UIKeyboardTypeNumbersAndPunctuation, standard phone keyboard, supporting + * # characters

UIKeyboardTypeURL, URL keyboard,. com button supported only URL characters

UIKeyboardTypeNumberPad, numeric keypad

UIKeyboardTypePhonePad, telephone keyboard

UIKeyboardTypeNamePhonePad, a telephone keyboard, or a personal name

UIKeyboardTypeEmailAddress, which is used to enter the keyboard of the email address

UIKeyboardTypeDecimalPad, which has numbers and decimal points on the keyboard

UIKeyboardTypeTwitter, an optimized keyboard for easy entry of @ and # characters

UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable,

} UIKeyboardType;

 

// Whether the first letter is capitalized

Text. autocapitalizationType = UITextAutocapitalizationTypeNone;

 

Typedef enum {

UITextAutocapitalizationTypeNone, which is not automatically capitalized

UITextAutocapitalizationTypeWords, uppercase letters

UITextAutocapitalizationTypeSentences. The first letter of a sentence is capitalized.

UITextAutocapitalizationTypeAllCharacters, all uppercase letters

} UITextAutocapitalizationType;

 

// What is the return key?

Text. returnKeyType = UIReturnKeyDone;

 

Typedef enum {

UIReturnKeyDefault: the default gray button marked with Return

UIReturnKeyGo, marked with the Go blue button

UIReturnKeyGoogle, marked with Google's blue button, term search

UIReturnKeyJoin, marked with the blue button of Join

UIReturnKeyNext, marked with the blue button Next

UIReturnKeyRoute, marked with the Route blue button

UIReturnKeySearch, marked with the blue button of Search

UIReturnKeySend, marked with the Send blue button

UIReturnKeyYahoo, marked with the Yahoo blue button

UIReturnKeyYahoo, marked with the Yahoo blue button

UIReturnKeyEmergencyCall, emergency call button

} UIReturnKeyType;

 

// Keyboard appearance

TextView. keyboardAppearance = UIKeyboardAppearanceDefault;

Typedef enum {

UIKeyboardAppearanceDefault, default appearance, light gray

UIKeyboardAppearanceAlert, dark gray Graphite

 

} UIReturnKeyType;

 

 

// Sets the proxy to implement the Protocol.

Text. delegate = self;

 

// Add textfield to the view

[Self. window addSubview: text];

 

// Add the image to the rightmost side, which is similar to the following code on the left.

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 becomeFirstResponder.

 

Class must use 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 [receiver resignFirstResponder] which can be called to push down the keyboard corresponding to the receiver

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 painting text attributes. When rewriting, you can call super to draw based on the default graphic attributes. If you completely rewrite the painting function, you do not need to call super.

-PlaceholderRectForBounds: // rewrite to reset the placeholder Area

-DrawPlaceholderInRect.

-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 to specify whether to edit the text field in sequence.

Return YES;

}

 

-(Void) textFieldDidBeginEditing :( UITextField *) textField {

 

// Triggered when editing starts. The text field becomes first responder

}

 

-(BOOL) textFieldShouldEndEditing :( UITextField *) textField {

 

// Return the BOOL value to specify whether to allow end editing of text fields. When the editing ends, the text field will give the first responder

// If you want to stop the text field from disappearing when the user finishes editing, NO can be returned.

// This is useful for some programs whose text fields must always be active, such as instant messages.

Return NO;

}

 

-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string {

 

// This method is called when the user uses the automatic correction function to change the input text to the recommended text.

// This is especially useful for applications that want to add revocation options

// You can trace the last modification made to a field or make a log record for All edits for auditing purposes.

// NO can be returned to prevent text changes

// The parameter of this method has a nsange object, indicating the location of the modified text. The recommended text is also in it.

 

Return YES;

}

 

-(BOOL) textFieldShouldClear :( UITextField *) textField {

 

// Return a BOOL value to indicate whether content can be cleared based on user requests

// You can specify conditions to allow content clearing.

 

Return YES;

}

 

-(BOOL) textFieldShouldReturn :( UITextField *) textField {

 

// Return a BOOL value indicating whether to allow editing to end when you press the Enter key

// If you are allowed to call the resignFirstResponder method, this will end the editing, and 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

 

UITextFieldTextDidBeginEditingNotification

UITextFieldTextDidChangeNotification

UITextFieldTextDidEndEditingNotification

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 // sent before display on the keyboard

UIKeyboardDidShowNotification // send after displaying the keyboard

UIKeyboardWillHideNotification // sent before hiding the keyboard

UIKeyboardDidHideNotification // send after the keyboard is hidden

 

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 shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string {

NSCharacterSet * cs;

Cs = [[NSCharacterSet characterSetWithCharactersInString: NUMBERS] invertedSet];

 

NSString * filtered = [string componentsSeparatedByCharactersInSet: cs] componentsJoinedByString: @ "]; // splits the array by cs, and splits the array @""

 

BOOL canChange = [string isEqualToString: filtered];

 

Return 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 that this \ n. If this is not set, the Done button will not be triggered. If it is used in the SearchBar, it will not trigger the Search event, because you will not allow the input \ n by yourself. It is so miserable that I found it in the project .)

Therefore, if you want to restrict the input of English letters and numbers, you can define this:

# 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 input at this time. It is the input box that is being input at this time. If YES is returned, the value of NO in the input box can be changed.

If ([string isEqualToString: @ "\ n"]) // you can change the value based on the selected vehicle.

{

Return YES;

}

 

NSString * toBeString = [textField. text stringByReplacingCharactersInRange: range withString: string]; // get the content of the input box

 

If (self. myTextField = textField) // specifies the input box we want to limit when determining whether or not

{

If ([toBeString length]> 20) {// if the content of the input box is greater than 20, a warning is displayed.

TextField. text = [toBeString substringToIndex: 20];

UIAlertView * alert = [[UIAlertView alloc] initWithTitle: nil message: @ "you cannot enter" delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil] autorelease];

[Alert show];

Return NO;

}

}

Return YES;

}

 

 

Reproduced http://blog.csdn.net/tskyfree/article/details/8121915/

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.