OC developing iOS Code Snippets

Source: Internet
Author: User

1. Code that determines whether the mailbox is formatted correctly

Using 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 = U Igraphicsgetimagefromcurrentimagecontext ();//End the Contextuigraphicsendimagecontext ();//Return The new Image.return NewImage;}


3. Pro-Test the 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 (@ "number of 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 images to ImageView

UIImage *myimage = [UIImage 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];p icker.delegate = self;picker.allowsEditing= Yes;picker.sourcetype=sourcetype; [Self presentmodalviewcontroller:picker animated:yes];

Select 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 the method that you define for yourself, edit the effect you want to achieve after selecting a photo
Cancel Selection:

-(void) Imagepickercontrollerdidcancel: (uiimagepickercontroller*) Picker{[picker Dismissmodalviewcontrolleranimated:yes];}


6. Skip to the next view

Nextwebview = [[Webviewcontroller alloc] initwithnibname:@ "Webviewcontroller" bundle:nil]; [Self Presentmodalviewcontroller:nextwebview animated:yes];//Create a Uibarbuttonitem right button uibarbuttonitem *rightButton = [[Uibarbuttonitem alloc] initwithtitle:@ "right" style:uibarbuttonitemstyledone target:self action: @selector ( Clickrightbutton)]; [Self.navigationitem Setrightbarbuttonitem:rightbutton]; Set Navigationbar Hide Self.navigationController.navigationBarHidden = Yes;//ios Development Uilabel Multiline text wrap (auto-fold 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 settingLabel.linebreakmode = Uilinebreakmodewordwrap;label.numberoflines = 0; 


7. Code Generation button

CGRect frame = CGRectMake (0, 400, 72.0, 37.0); UIButton *button = [UIButton buttonwithtype:uibuttontyperoundedrect];button.frame = frame; [Button settitle:@ "newly added buttons" Forstate:uicontrolstatenormal];button.backgroundcolor = [Uicolor Clearcolor];button.tag = 2000; [Button addtarget:self action: @selector (buttonclicked:) forcontrolevents:uicontroleventtouchupinside]; [Self.view Addsubview:button];


8. Make a control appear in the center of the View
(a control, such as Label,view) Label.center = Self.view.center;

9. Good-looking word processing

Take the Textlabel of the cell in TableView as an example:

Cell.backgroundcolor = [uicolorscrollviewtexturedbackgroundcolor];//Sets the font of the text Cell.textLabel.font = [Uifont fontwithname:@ "Americantypewriter" size:100.0f];//set the color of the text Cell.textLabel.textColor = [Uicolor orangecolor];// Sets the background color of the text Cell.textLabel.shadowColor = [Uicolor whitecolor];//sets the display position of the text cell.textLabel.textAlignment = Uitextalignmentcenter;


10. Hide Status Bar
The reader may know an easy way to add a viewdidload to the program.

[[UIApplication Sharedapplication]setstatusbarhidden:yes Animated:no];


11. Change the Alertview background

Uialertview *thealert = [[[Uialertviewalloc] initwithtitle:@ "atention" message: @ "I ' m a chinese!" delegate:nilcancelbuttontitle:@ "Cancel" otherbuttontitles:@ "Okay", Nil] autorelease]; [Thealert show]; UIImage *theimage = [uiimageimagenamed:@ "lovechina.png"];theimage = [Theimage stretchableimagewithleftcapwidth:0 TOPCAPHEIGHT: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];


12. Keyboard transparency

Textfield.keyboardappearance = Uikeyboardappearancealert;

Network activity on the status bar whether the wheel rotates

[UIApplication sharedapplication].networkactivityindicatorvisible, the default value is No.


13. Capturing Screen Images
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 graphics context uiimage *aimage = Uigraphicsgetimagefromcurrentimagecontext ();//Remove 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);


14. Change the background of cell selection

UIView *myview = [[UIView alloc] init];myview.frame = CGRectMake (0, 0, +); myview.backgroundcolor = [Uicolorcolorwith Patternimage:[uiimage imagenamed:@ "0006.png"]];cell.selectedbackgroundview = MyView;


15. Displaying images

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];


16. Can make the picture fit the box size (no confirmation)

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];


17. Implement the code to jump by clicking on the image: Generate a button with a background image and bind the desired event to the button!

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];

OC developing iOS Code Snippets

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.