Uitextfield in iOS with full parsing

Source: Internet
Author: User

Initialize TextField and set location and size

Uitextfield *text = [[Uitextfield alloc]initwithframe:cgrectmake (20, 20, 130, 30)]; The border style is set only if the border style is set text.borderstyle = Uitextborderstyleroundedrect; typedef enum {uitextborderstylenone, Uitextborderstyleline, Uitextborderstylebezel, uitextborderstylerounded Rect} Uitextborderstyle; Sets the background color of the input box, when set to white if you use a custom background pictureBorderwill be ignored text.backgroundcolor = [Uicolor Whitecolor]; Set Background Text.background = [UIImage imagenamed:@ "Dd.png"]; Set the background text.disabledbackground = [UIImage imagenamed:@ "Cc.png"];//when the input box does not have content, the watermark prompt content is password text.placeholder = @ "Pa ssWOrd "; Sets the font style and size of the input box contents Text.font = [Uifont fontwithname:@ "Arial" size:20.0f]; Set Font Color Text.textcolor = [UicolorRedcolor]; //If there is a fork in the input box, when it is displayed, to delete the contents of the input box at once   Text.clearbuttonmode = uitextfieldviewmodealways;  typedef enum {    Uitextfieldviewmodenever, not appearing     uitextfieldviewmodewhileediting,  editing     uitextfieldviewmodeunlessediting, except for edits     Uitextfieldviewmodealways always appears} uitextfieldviewmode; //input box in the beginning of the text   Text.text = @ "The beginning of the text in the input box,"  //each input a character becomes point   password input   Text.securetextentry = yes; //Error correction   Text.autocorrectiontype = Uitextautocorrectiontypeno; typedef Enum {    uitextautocorrectiontypedefault,  default     Uitextautocorrectiontypeno, no automatic error correction     Uitextautocorrectiontypeyes, auto error correction} uitextautocorrectiontype; //erase   text.clearsonbeginediting = yes;  //content Alignment   Text.textalignment = vertical alignment of uitextalignmentleft; //content   Uitextfield inherits from Uicontrol, which has an attribute contentverticalalignment  text.contentverticalalignment = UicontrolcontentverticalWhen alignmentcenter; //is set to YES, the text automatically shrinks to fit the text window size. The default is to keep the original size while letting long text scroll   textfied.adjustsfontsizetofitwidth = YES;  //set the minimum font size for the auto-shrink display   Text.minimumfontsize = 20; //Set the keyboard style   Text.keyboardtype = uikeyboardtypenumberpad; typedef enum {    Uikeyboardtypedefault,     default keyboard, all characters supported              uikeyboardtypeasciicapable, ASCII-enabled default keyboard     Uikeyboardtypenumbersandpunctuation, standard telephone keypad, support +*# characters     uikeyboardtypeurl,             URL keypad, support for. com buttons   only URL characters uikeyboardtypenumberpad,             Numeric keypad uikeyboardtypephonepad, telephone keypad     UIKEYBOARDTYPENAMEPHONEPAD, telephone keypad, also support input person name uikeyboardtypeemailaddress, For input electronics  e-mail addressThe keyboard uikeyboardtypedecimalpad,Numeric Keypad  Digital and decimal     uikeyboardtypetwitter,      optimized keyboard for easy input @, #字符     Uikeyboardtypealphabet = uikeyboardtypeasciicapable, } uikeyboardtype; //first Letter capital   Text.autocapitalizationtype = uitextautocapitalizationtypenone; typedef enum {    uitextautocapitalizationtypenone,  do not automatically capitalize     Uitextautocapitalizationtypewords, capitalize the first letter of the word     Uitextautocapitalizationtypesentences, first letter of sentence     uitextautocapitalizationtypeallcharacters,  All letters are capitalized} Uitextautocapitalizationtype; //return key becomes what key  text.returnkeytype =uireturnkeydone;   typedef enum {    uireturnkeydefault,  default   Gray button, labeled return    uireturnkeygo,    Blue button labeled Go     uireturnkeygoogle, blue button labeled Google, search     Uireturnkeyjoin, blue button with join     Uireturnkeynext, blue button labeled next     Uireturnkeyroute, blue button labeled route     Uireturnkeysearch, Blue button labeled Search     Uireturnkeysend, MarkBlue button with Send     Uireturnkeyyahoo, blue button labeled Yahoo     Uireturnkeyyahoo, blue button with Yahoo!     uireturnkeyemergencycall,  Emergency call Button} uireturnkeytype; //keyboard appearance textview.keyboardappearance= Uikeyboardappearancedefault;typedef enum {uikeyboardappearancedefault,  default appearance, Light gray uikeyboardappearancealert, dark grey   graphite  } uireturnkeytype;  //setting proxy   for implementing protocol   Text.delegate = self; //Adding TextField to the view   [Self.window addsubview:text]; //the rightmost plus picture is the following code   left like     Uiimageview *image=[[uiimageview Alloc] initwithimage:[uiimage imagenamed:@ "right.png"]];    text.rightview=image;    Text.rightviewmode = uitextfieldviewmodealways;  typedef enum {    Uitextfieldviewmodenever,     uitextfieldviewmodewhileediting,    uitextfieldviewmodeunlessediting,    Uitextfieldviewmodealways} uitextfieldviewmode;  //Press RETURN key to receive   becomefirstresponder  class to use UitextfielddelegaTE protocol  text.delegate = self; Declare the text of the agent is me, I will go to achieve the keyboard down the method   This method in uitextfielddelegate so we have to adopt uitextfielddelegate this protocol  -(BOOL) Textfieldshouldreturn: (Uitextfield *) textfield{    [text resignfirstresponder];   //main [ Receiver Resignfirstresponder] Where to call the receiver corresponding to the keyboard down

return YES;

In addition to the style options of the Uitextfield object, you can also customize the Uitextfield object, adding a number of different rewrite methods to change the display behavior of the text field. All of these methods return a CGRECT structure that has a boundary range for each part of the text field. The following methods can be overridden. –textrectforbounds://Rewrite to reset the text area –drawtextinrect://Change the Emoji property. When overridden, calling super can be drawn by default drawing properties, and you don't have to call super if you completely override the drawing function. –pl Aceholderrectforbounds://Override to reset Placeholder area –drawplaceholderinrect://Override to change the draw placeholder property. When overridden, calling Super can press the defaultGraphicsProperty drawing, if you completely rewrite the drawing function, you do not have to call super. – borderrectforbounds://Override to reset the Edge area – editingrectforbounds://Override to reset the editing area –  clearbuttonrectforbounds://Rewrite to reset the Clearbutton position, changing the size may cause the picture of the button to be distorted – leftviewrectforbounds:–    rightviewrectforbounds:  Delegate Method  -  (BOOL) textfieldshouldbeginediting: (uitextfield *) textfield{ Returns a bool value that specifies whether the sequential text field begins editing     return yes; }  -  (void) textfielddidbeginediting: (uitextfield *) textfield{ //starts editing and the text field becomes first  Responder}  -  (BOOL) textfieldshouldendediting: (uitextfield *) textfield{//Returns BOOL value, specifies whether the text field is allowed to end the edit,  When the edit is finished, the text field will yield First responder  //to prevent the text field from disappearing when the user finishes editing, you can return no  //this is useful for programs that must remain active for some text fields, such as instant messaging      return no; }  -  (BOOL) TextField: (uitextfield*) Textfield shouldchangecharactersinrange: (Nsrange) range  Replacementstring: (nsstring *) string{//This method is called when the user uses the AutoCorrect feature to modify the input text to the recommended text. This is especially useful for applications that want to join the Undo option//Can track the last modification made in a field, you can also log records for all edits for auditing purposes.  //to prevent text from being changed you can return no//The parameter of this method has a Nsrange object that indicates the position of the changed text, and the suggested text is also in it     return yes; }  -  (BOOL) Textfieldshouldclear: (uitextfield *) textfield{ //Returns a BOOL value indicating whether the content is allowed to be purged based on user request/ Can be set under certain conditions to allow clear content     return yes; }  -(BOOL) Textfieldshouldreturn: (uitextfield *) textfield{ //Returns a BOOL value indicating whether the edit is allowed to end when the ENTER key is pressed  // If you allow the resignfirstresponder  method to be called, this causes the end of the edit and the keyboard will be closed [textfield resignfirstresponder];// Check out the meaning of the word 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 a text field. In addition to the standard events of the Uicontrol class, you can also use the following Uitextfield class-specific events   Uitextfieldtextdidbegineditingnotificationuitextfieldtextdidchangenotificationuitextfieldtextdidendeditingnotification when text triggered when the field exits edit mode. The object property of the notification stores the final text.   Because text fields use the keyboard to enter text, action notifications are also sent when the following events occur  uikeyboardwillshownotification// Keyboard display before sending uikeyboarddidshownotification //keyboard display after sending Uikeyboardwillhidenotification//keyboard hidden before sending Uikeyboarddidhidenotification //keyboard is hidden after sending 1, text : Sets the default text for the text box. 2. placeholder :  can display gray words in the text box to indicate what the user should enter in the text box. When you enter data in this text box, the gray words for the hint will automatically disappear. 3, Background :4, disabled :  If this item is selected, the user will not be able to change the contents of the text box. 5. Next, there are three buttons to set the alignment. 6, Border style :  Select the border style. 7, clear button :  This is a drop-down menu, you can choose to clear when the button appears, the so-called clear button is out of a text box to the right of the small  x&nbsp, you can have the following options:    7.1 Never appears :  never appears     7.2 appears while editing :  editing occurs     7.3 appears unless E diting :     7.4 are always visible :  visible 8, Clear when editing begins :  if this item is selected, When you start editing the text box, the previous content in the text box is erased. For example, you are now in this text box  A  entered   "What" &nbsp, and then to edit the text box  b, if you come back to edit the text box  a&nbsp, then the   "what"   will be cleared immediately. 9. Text color :  sets the color of the text in the text box. 10. font :  sets the font and font size of the text. 11, Min Font size :  set the minimum font that the text box can display (but I don't feel like it) 12, Adjust to fit :  specifies whether the text in the text box shrinks when the size of the text box decreases. Select it to make all text visible, even if the text is long. But this option has to do with  min Font size With the use, the text shrinks again and will not be less than the set  min Font size . The next sections are used to set how the keyboard is displayed. 13, captitalization :  set uppercase. There are four options in the drop-down menu:    13.1 none :  do not set caps     13.2 words :  Each word is capitalized, the word here refers to a string separated by a space     13.3 sentances :  The first letter of each sentence, where the sentence is the string separated by a period and a space     13.4 all characters :   So letter Capital 14, correction :  check spelling, default is  YES . 15, keyboard :  Select keyboard type, such as full numbers, letters and numbers. 16, Appearance:17, return key :  Select the Return key, you can select  Search ,  Return ,  Done  and so on. 18, Auto-enable return key :  If this option is selected, the keyboard's return key is valid only if at least one character is entered in the text box. 19, secure :  When your text box is used as a password input box, you can select this option, at which point the characters are displayed as asterisks.  1.alignment horizontal  Horizontal Alignment 2. Alignment vertical  Vertical Alignment 3. Returns a bool value if the input box is  selected (checked) Enabled (available) highlighted (highlight)   limit only specific characters can be entered   (BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) range replacementstring: ( NSString *) string{    Nscharacterset *cs;    CS =[[Nscharacterset charactersetwithcharactersinstring:numbers]invertedset];     NSString *filtered = [[ String componentsseparatedbycharactersinset:cs]componentsjoinedbystring:@ ""]; //groups separated by CS, array separated by @ ""      BOOL canchange = [string Isequaltostring:filteRed]; return canchange;} The above NUMBERS is a macro, can be defined at the top of the file: #define NUMBERS @ "0123456789n" (this representative can enter numbers and newline, please note that this n, if you do not write this, doneKeyWill not be triggered, if used in Searchbar, will not trigger the search event, because you limit the input n, it is very sad, I found in the project. So, if you want to restrict the input of English and numbers, you can define this as: #define Kalphanum   @ " Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789″. Of course, you can also make a hint before the above method return, such as prompting the user to enter only numbers. If you feel the need.   Restrict the input of a certain length of character  -(BOOL) TextField: (Uitextfield *) TextField Shouldchangecharactersinrange: (nsrange) Range Replacementstring: (NSString *) string; {//string is the character entered at this time  textfield is the input box being entered at this time   Return Yes to change the value of the input box  no the opposite  if ([string isequaltostring:@ "n"])//press passing to change     {         return yes;    }      NSString * tobestring = [Textfield.text stringbyreplacin Gcharactersinrange:range withstring:string]; //Get the contents of the input box      if (Self.mytextfield = = TextField)// Determine if we want to limit the input box     {         if ([tobestring length] >) { //If the input box content is greater than 20 Out warning   textfield.text = [Tobestring substringtoindex:20];            Uialertview *alert = [[[Uialertview alloc] Initwithtitle:nil message:@ "The maximum number of words cannot be entered" Del Egate:nil cancelbuttontitle:@ "OK" otherbuttontitles:nil, nil] autorelease];           & nbsp [Alert show];             return no;        }   &NB Sp }     return yes; }

Full parsing of Uitextfield use in iOS

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.