Uitextfiled Comprehensive parsing in IOS

Source: Internet
Author: User
Tags set background uicontrol

Initialize TextField and set location and size

  Uitextfield *text = [[[Uitextfield Alloc]initwithframe:cgrectmake]]; //set border style, only set to show border style   Text.borderstyle = Uitextborderstyleroundedrect; typedef enum {    uitextborderstylenone,     uitextborderstyleline,    uitextborderstylebezel,    Uitextborderstyleroundedrect   } uitextborderstyle; Sets the background color of the input box, which is set to white   If you use a custom background picture border is ignored Text.backgroundcolor = [uicolor whitecolor]; //setting background   Text.background = [UIImage imagenamed:@ "Dd.png"]; //set background    text.disabledbackground = [UIImage imagenamed:@ "Cc.png"];//when the input box does not have content, the watermark prompt   prompt content is password  text.placeholder = @ "password";  // Set font style and size for input box contents   Text.font = [Uifont fontwithname:@ "Arial" size:20.0f]; //set font color   Text.textcolor = [ Uicolor redcolor]; //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, heavy no-show &nbsp   uitextfieldviewmodewhileediting,  When editing appears     uitextfieldviewmodeunlessediting, except edit appears     Uitextfieldviewmodealways always appear} uitextfieldviewmode; //in the input box at the beginning of the text   Text.text = @ "The beginning of the text in the input box";  //each input character into a point   phrase password input   Text.securetextentry = yes; //Error correction   Text.autocorrectiontype = uitextautocorrectiontypeno; typedef enum {    uitextautocorrectiontypedefault,  default     Uitextautocorrectiontypeno, no automatic error correction     Uitextautocorrectiontypeyes, auto error correction} uitextautocorrectiontype; // Edit again to clear   text.clearsonbeginediting = yes;  //content alignment   text.textalignment = Uitextalignmentleft; The vertical alignment of the  //content   Uitextfield inherits from Uicontrol, which has an attribute in the class contentverticalalignment  Text.contentverticalalignment = uicontrolcontentverticalalignmentcenter; // When 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 display to automatically zoom out   Text.minimumfontsize = 20 //set keyboard style   Text.keyboardtype = uikeyboardtypenumberpad; typedef enum {    Uikeyboardtypedefault,     default keyboard, all characters are supported              Uikeyboardtypeasciicapable, default keyboard for ASCII     uikeyboardtypenumbersandpunctuation, standard telephone keypad, support for +*# characters     uikeyboardtypeurl,            URL keypad, support for. com buttons   Only URL characters are supported uikeyboardtypenumberpad,            Numeric keypad uikeyboardtypephonepad, telephone keypad   &NBSP ; Uikeyboardtypenamephonepad, telephone keypad, also supports input person name uikeyboardtypeemailaddress, keyboard       for entering electronic   e-mail addresses Uikeyboardtypedecimalpad,   Numeric keypad   keyboards with numbers and decimal points     uikeyboardtypetwitter,      Optimized Easy to enter @, #字符     Uikeyboardtypealphabet = uikeyboardtypeasciicapable, } uikeyboardtype; //First Letter uppercase   Text.autocapitalizationtype = uitextautocapitalizationtypenone; typedef enum {    uitextautocapitalizationtypenone, Do not automatically capitalize     Uitextautocapitalizationtypewords, capitalize the first letter of the word     uitextautocapitalizationtypesentences, The first letter of the sentence     uitextautocapitalizationtypeallcharacters,  all letters in uppercase} Uitextautocapitalizationtype;  //return key into what key  text.returnkeytype =uireturnkeydone; typedef enum {    UIReturnKeyDefault,   Default   Gray button, labeled return    uireturnkeygo,    blue button     Uireturnkeygoogle for Go Blue button labeled Google, search     Uireturnkeyjoin, blue button labeled join     Uireturnkeynext, blue button with next     Uireturnkeyroute, blue button labeled route     Uireturnkeysearch, blue button with search     Uireturnkeysend, Blue button labeled 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 Color &nbsP;} uireturnkeytype;  //set proxy   for implementing protocol   Text.delegate = self; //add TextField to view   [ Self.window addsubview:text]; //The rightmost 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 adopt 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;

}   rewrite the paint behavior in addition to the Uitextfield object's style options, you can also customize the Uitextfield object and add many different rewrite methods to it 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 text area – drawtextinrect:      // Changes the emoji property. Calling super When overridden can be drawn by default drawing properties, and you don't have to call super if you completely override the drawing function. – placeholderrectforbounds://Override to reset the placeholder area –  Drawplaceholderinrect://Override to change the draw placeholder property. When overridden, calling super can be drawn by default drawing properties, so you don't have to call super if you completely override the drawing function. – borderrectforbounds:/ /override to reset the Edge area – editingrectforbounds://Override to reset the editing area – clearbuttonrectforbounds://Override to reset the Clearbutton location, Changing the size of a button can cause the picture to distort – leftviewrectforbounds:– rightviewrectforbounds:  delegate method  -  (BOOL) Textfieldshouldbeginediting: (uitextfield *) textfield{//Returns a bool value that specifies whether the sequential text field starts editing     return  YES; }  -  (void) textfielddidbeginediting: (uitextfield *) textfield{ //starts editing and the text field becomes first  Responder}  -  (BOOL) textfieldshouldendediting: (uitextfield *) textfield{//return BOOL value,Specifies whether the text field is allowed to end editing, and when the edit is finished, the text field yields First responder  //to prevent the text field from disappearing when the user finishes editing, you can return no  // This is useful for programs where text fields must always remain active, 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//You can track the last modification made in a field, or you can log 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 derived from Uicontrol, so the notification system in the Uicontrol classcan also be used in text fields. 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 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 selected, the previous contents of the text box will be erased when you start editing the text box. 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. However, this option should be used in conjunction with  min font size , and the text will not be smaller 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 will be returned only if at least one character is entered in the text boxonly works. 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:@ ""]; //separate groups by CS, array by @ "" to isolate the string       BOOL canchange = [string isequaltostring:filtered];     return canchange;}   Above that 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 n, if you do not write this, the Done button will not trigger, If it is used in Searchbar, the search event will not be triggered because you are restricting the input to n, and I found it 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" Delegate:nil cancelbuttontitle:@ "OK" OtherbuttontitLes:nil, Nil] autorelease];             [alert show];             return no;        }    }     return Yes; }&nbs  p;  another: When the text box is entered, there is no space required for the input string, no Chinese, but there is no setting in the Uikeyboardtype can directly meet this requirement, then can only use the protocol rewrite restrictions.  1, Uikeyboardtype set to uikeyboardtypeasciicapable: Support ASCII default keyboard 2, implement uitextfiled protocol. Finally, put the code on ...
/*!breif * Limit the text input box input length and prohibit input space * @param string input strings * @param textField the current text input box * @param range * @param legth the length of the allowed input */+ (BO OL) verificationtextfiledstring: (NSString *) string Withtext: (Uitextfield *) TextField Withrange: (nsrange) Range    Withlength: (nsinteger) legth{nscharacterset *cs;    CS = [[Nscharacterset charactersetwithcharactersinstring:kalphanum] invertedset];    NSString *filtered = [[string Componentsseparatedbycharactersinset:cs] componentsjoinedbystring:@ ""]; BOOL basic = [string isequaltostring:filtered];//whether the input is a number or a letter if (Basic==yes) {if ([string isequaltostring:@] \ n        "]) {//press ENTER to change return YES;                } nsstring *tobestring=[textfield.text Stringbyreplacingcharactersinrange:range withString:string];        NSLog (@ "BES---%@", tobestring);            if ([tobestring length]>legth) {textfield.text=[tobestring substringtoindex:legth];        return NO;    }}else{return NO; } return YES;

Uitextfiled Comprehensive parsing 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.