Some useful little code in IOS development

Source: Internet
Author: User

1. Determine the correct format of the Mailbox code://Use Regular expression validation-(BOOL) Isvalidateemail: (nsstring *) Email{ nsstring *emailregex =  @ "[a-z0-9a-z._%+-][email protected][a-za-z0-9.-]+\\. [A-za-z] {2,4} ";  nspredicate *emailtest = [nspredicate predicatewithformat:@" Self matches%@ ", EmailRegex];  return [emailtest evaluatewithobject:email];}  2. Image compression   Usage: UIImage *yourimage= [self imagewithimagesimple:image scaledtosize:cgsizemake (210.0, 210.0)];// Compress picture-(uiimage*) Imagewithimagesimple: (uiimage*) Image scaledtosize: (cgsize) newsize{//Create a graphics image Contextuigraphicsbeginimagecontext (newSize);  //tell the old image to draw in this newcontext, with the desired//new Size[image drawinrect:cgrectmake (0,0,newsize.width,newsize.height)]; //Get The new image from the contextuiimage* newimage = uigraphicsgetimagefromcurrentimagecontext ();  //End Contextuigraphicsendimagecontext ();  //Return the new Image.return newimage;}   3. ProTest available image upload code-(ibaction) Uploadbutton: (ID) Sender {uiimage *image = [uiimage imagenamed:@ "1.jpg"]; Picture name Nsdata *imagedata = uiimagejpegrepresentation (image,0.5);//Compression ratio nslog (@ "bytes:%i", [imageData length]) ;//Post urlnsstring *urlstring = @ "Http://192.168.1.113:8090/text/UploadServlet";//server address//setting up the Request Object nownsmutableurlrequest *request = [[Nsmutableurlrequest alloc] init]; [request seturl:[nsurl urlwithstring:urlstring]]; [request sethttpmethod:@ "POST"];//nsstring *boundary = [nsstring stringwithstring:@ "------------- --------------14737809831466499882746641449 "]; Nsstring *contenttype = [nsstring stringwithformat:@ "multipart/form-data;boundary=%@", boundary]; [request addvalue:contenttype forhttpheaderfield: @ "content-type"];//NSMutableData *body = [ nsmutabledata data]; [body appenddata:[[nsstring stringwithformat:@ "\r\n--%@\r\n", boundary] datausingencoding:nSutf8stringencoding]]; [body appenddata:[[nsstring stringwithstring:@ "Content-disposition:form-data; name=\" Userfile\ "; Filename=\ "2.png\" \ r \ n "] datausingencoding:nsutf8stringencoding]]; Uploaded image name [body appenddata:[[nsstring stringwithstring:@] content-type:application/octet-stream\r\n\ r\n "] datausingencoding:nsutf8stringencoding]]; [body appenddata:[nsdata datawithdata:imagedata]]; [body appenddata:[[nsstring stringwithformat:@ "\r\n--%@--\r\n", boundary] datausingencoding: nsutf8stringencoding]];  [request sethttpbody:body]; //NSLog (@ "1-body:%@", body); NSLog (@ "2-request:%@", request);  nsdata *returndata = [Nsurlconnection sendsynchronousrequest: request returningresponse:nil error:nil]; nsstring *returnstring = [[nsstring alloc] initwithdata:returndata encoding: Nsutf8stringencoding]; NSLog (@ "3-Test output:%@", returnstring);   4. Load Picture ImageView = [Uiimage *myimagee imagenamed:@ "1.jpg"];   [imageview setimage:myimage];   [self.view  Addsubview:imageview]; 5. Working with the Gallery Select album: uiimagepickercontrollersourcetypesourcetype= uiimagepickercontrollersourcetypecamera;   if (![ Uiimagepickercontrollerissourcetypeavailable:uiimagepickercontrollersourcetypecamera]) {       sourcetype=uiimagepickercontrollersourcetypephotolibrary;  }   Uiimagepickercontroller * Picker = [[uiimagepickercontrolleralloc]init];   Picker.delegate = self;    picker.allowsediting=yes;   picker.sourcetype=sourcetype;   [self Presentmodalviewcontroller:picker Animated:yes]; Selection complete:  -(void) Imagepickercontroller: ( uiimagepickercontroller*) Pickerdidfinishpickingmediawithinfo: (nsdictionary *) info{   [picker dismissmodalviewcontrolleranimated:yes];   UIImage * Image=[info Objectforkey: uiimagepickercontrollereditedimage];   [Self Performselector: @selector (selectpic:) withobject:imageafterdelay:0.1];}  -(void) Selectpic: (uiimage*) image{   NSLog (@ "image%@", image);    ImageView = [[ Uiimageview alloc] initwithimage:image];   imageview.frame = CGRectMake (0, 0, Image.size.width, Image.size.height); [self.viewaddsubview:imageview];   [Self Performselectorinbackground: @selector (Detect:) Withobject:nil] ;} Detect for the method you define, edit the effect you want to achieve after selecting the photo deselect:  -(void) Imagepickercontrollerdidcancel: (uiimagepickercontroller*) Picker
{[Picker dismissmodalviewcontrolleranimated:yes];} 6. Skip to the next Viewnextwebview = [[Webviewcontroller alloc] initwithnibname:@ "Webviewcontroller" bundle:nil]; [Self Presentmodalviewcontroller:nextwebview animated:yes];

  7. Create a Uibarbutton right button Uibarbuttonitem *rightbutton = [[uibarbuttonitem alloc]  initwithtitle:@ "Right"  style:uibarbuttonitemstyledone target:self action: @selector ( Clickrightbutton)]; [Self.navigationitem setrightbarbuttonitem:rightbutton];  8. Set Navigationbar hidden Self.navigationcontroller.navigationbarhidden = yes;// 9.uilabel multiline text wrap   (Automatic folding line) UIView *footerview = [[UIView alloc]initwithframe:cgrectmake (10, 100, 300, 180)]; UILabel *label = [[UILabel alloc]initwithframe:cgrectmake]];label.text = @ "Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Helloworld! "; /Background color is red Label.backgroundcolor = [uicolor redcolor];//set font color to white label.textcolor = [Uicolor whitecolor];// Text centered display label.textalignment = uitextalignmentcenter;//auto-wrap settings label.linebreakmode = uilinebreakmodewordwrap; Label.numberoflines = 0;   10. Code Generation Buttoncgrect frame = cgrectmake (0, 400, 72.0, 37.0); Uibutton *button = [uibutton buttonwithtype:uibuttontyperoundedrect];button.frame = frame; [button settitle:@ "Newly added button"  forstate: uicontrolstatenormal];button.backgroundcolor = [ uicolor clearcolor];button.tag = 2000; [Button addtarget:self action: @selector (buttonclicked:)  forcontrolevents: UIControlEventTouchUpInside]; [Self.view addsubview:button];  11. Let a control appear in the center of the View: (a control, such as Label,view) label.center =  self.view.center; 12. Customizing text various effects: Cell.backgroundcolor = [Uicolorscrollviewtexturedbackgroundcolor];
Set font for text
Cell.textLabel.font = [Uifont fontwithname:@ "Americantypewriter" size:100.0f];
Set the color of text
Cell.textLabel.textColor = [Uicolor Orangecolor];
Set the background color of text
Cell.textLabel.shadowColor = [Uicolor Whitecolor];
Set where text is displayed
Cell.textLabel.textAlignment = Uitextalignmentcenter; 13. Hide StatusBar:
Add in the Viewdidload of the program
[[UIApplication Sharedapplication]setstatusbarhidden:yes Animated:no]; 14. Change the Alertview background:
Uialertview *thealert = [[[Uialertviewalloc] initwithtitle:@ "Atention"
Message: @ "I ' m a chinese!"
Delegate:nil
cancelbuttontitle:@ "Cancel"
otherbuttontitles:@ "Okay", Nil] autorelease];
[Thealert show];
UIImage *theimage = [uiimageimagenamed:@ "Lovechina.png"];
Theimage = [Theimage stretchableimagewithleftcapwidth:0topcapheight:0];
Cgsize thesize = [Thealert frame].size;
Uigraphicsbeginimagecontext (thesize);
[Theimage Drawinrect:cgrectmake (5, 5, thesize.width-10, thesize.height-20)];//the size of this place to adjust itself to fit the size of the alertview background color.
Theimage = Uigraphicsgetimagefromcurrentimagecontext ();
Uigraphicsendimagecontext ();
TheAlert.layer.contents = (ID) [Theimage cgimage];
15. Keyboard Transparency:
Textfield.keyboardappearance = Uikeyboardappearancealert;

16. The network activity of the status bar whether the steamer rotates:
[UIApplication sharedapplication].networkactivityindicatorvisible, the default value is No. 17. Capture the screen image:
Creates a bitmap-based graphics context and specifies a size of Cgsizemake (200,400)
Uigraphicsbeginimagecontext (Cgsizemake (200,400));

Renderincontext renders the recipient and its child scopes to the specified context
[Self.view.layer Renderincontext:uigraphicsgetcurrentcontext ()];
Returns a picture based on the current drawing context
UIImage *aimage = Uigraphicsgetimagefromcurrentimagecontext ();
Removes the top of the stack based on the current bitmap's graphics context
Uigraphicsendimagecontext ();
Returns the data for the specified picture in PNG format
ImageData = Uiimagepngrepresentation (aimage); 18. Change the background of cell selection:
UIView *myview = [[UIView alloc] init];
Myview.frame = CGRectMake (0, 0, 320, 47);
Myview.backgroundcolor = [Uicolorcolorwithpatternimage:[uiimage imagenamed:@ "0006.png"];
Cell.selectedbackgroundview = myview;:19. Show Picture:
CGRect myimagerect = CGRectMake (0.0f, 0.0f, 320.0f, 109.0f);
Uiimageview *myimage = [[Uiimageview alloc] initwithframe:myimagerect];
[MyImage setimage:[uiimage imagenamed:@ "Myimage.png"];
Myimage.opaque = YES; Opaque is transparent
[Self.view Addsubview:myimage]; 20. Can make the picture fit box Size (Beta) nsstring*imagepath = [[NSBundle mainbundle] pathforresource:@ "Xcodecrash" oftype:@ "PNG"];
UIImage *image = [[UIImage Alloc]initwithcontentsoffile:imagepath];
UIImage *newimage= [Image transformwidth:80.f HEIGHT:240.F];
Uiimageview *imageview = [[Uiimageview alloc]initwithimage:newimage];
[Newimagerelease];
[Image release];
[Self.view Addsubview:imageview]; 21. Implement the code to jump by clicking on the image: (Generate a button with a background image to bind the button to the desired event) UIButton *imgbutton=[[uibutton Alloc]initwithframe:cgrectmake (0, 0, 120, 120)]; [Imgbutton setbackgroundimage: (UIImage *) [Self.imgarray ObjectAtIndex:indexPath.row] Forstate:uicontrolstatenormal];imgbutton.tag=[indexpath row]; [Imgbutton addtarget:self Action: @selector (ButtonClick:) forcontrolevents:uicontroleventtouchupinside]; 22. Keyboard recovery:-(ibaction) textfielddoneediting: (ID) sender{[sender Resighfirstrespond];} Recycle the keyboard by clicking on the background: (two must be added)-(ibaction) textfielddoneediting: (ID) sender{[sender resighfirstrespond];}- (ibaction) backgroundtapped: (ID) Sender{[namefield resignfirstrespond];[ Numberfield Resignfirstrespond];}

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.