Some useful little code in iOS development

Source: Internet
Author: User

1. code to determine whether the mailbox format is correct: // use a regular expression to verify-(BOOL) isValidateEmail :( NSString *) email {NSString * emailRegex = @ "[A-Z0-9a-z. _ % +-] + @ [A-Za-z0-9. -] + \\. [A-Za-z] {2, 4} "; NSPredicate * emailTest = [NSPredicate predicateWithFormat: @" self matches % @ ", emailRegex]; return [emailTest email];} 2. image compression usage: UIImage * yourImage = [self imageWithImageSimple: image scaledToSize: CGSizeMake (210.0, 210.0)]; // compressed image-(UI Image *) 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 = UIGraphicsGetImageFromCurrentImageContex T (); // End the contextUIGraphicsEndImageContext (); // Return the new image. return newImage;} 3. test the available image upload code-(IBAction) uploadButton :( id) sender {UIImage * image = [UIImage imageNamed: @ "1.jpg"]; // image 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 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: NSUTF 8 StringEncoding]; // name of the uploaded image [body appendData: [[NSString stringWithString: @ "Content-Type: application/octet-stream \ 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 image UIImage * myImage = [UIImage imageNamed: @ "1.jpg"]; [imageView setImage: myImage]; [se Lf. view addSubview: imageView]; 5. Select album for image library operations: UIImagePickerControllerSourceTypesourceType = UIImagePickerControllerSourceTypeCamera; if (! [Authorization: UIImagePickerControllerSourceTypeCamera]) {sourceType = UIImagePickerControllerSourceTypePhotoLibrary;} UIImagePickerController * picker = [[UIImagePickerControlleralloc] init. delegate = self; picker. allowsEditing = YES; picker. sourceType = sourceType; [self presentModalViewController: picker animated: YES]; selected:-(void) imagePickerController :( UIImageP IckerController *) Metadata :( NSDictionary *) info {[picker dismissModalViewControllerAnimated: YES]; UIImage * image = [info objectForKey: Custom]; [self defined mselector: @ selector (selectPic :) withObject: imageafterDelay: 0.1];}-(void) selectPic :( UIImage *) image {NSLog (@ "image % @", image); imageView = [[UIImageView alloc] initWithImage: image]; imageView. fr Ame = CGRectMake (0, 0, image. size. width, image. size. height); [self. viewaddSubview: imageView]; [self defined mselectorinbackground: @ selector (detect :) withObject: nil];} detect is a custom method. After editing and selecting a photo, deselect the effect: -(void) imagePickerControllerDIdCancel :( UIImagePickerController *) picker {[picker dismissModalViewControllerAnimated: YES];} 6. jump to the next ViewnextWebView = [[WEBViewController alloc] initWithNibName: @ "WEBVie WController "bundle: nil]; [self presentModalViewController: nextWebView animated: YES]; 7. create a UIBarButton UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithTitle: @ "right" style: UIBarButtonItemStyleDone target: self action: @ selector (clickRightButton)]; [self. navigationItem setRightBarButtonItem: rightButton]; 8. set navigationBar to hide self. navigationController. navigatio NBarHidden = YES; // 9. UIlabel multiline text wrap (automatic LINE folding) UIView * footerView = [[UIView alloc] initWithFrame: CGRectMake (10,100,300,180)]; UILabel * label = [[UILabel alloc] initWithFrame: CGRectMake (10,100,300,150)]; 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! "; // The background color is red label. backgroundColor = [UIColor redColor]; // set the font color to a white label. textColor = [UIColor whiteColor]; // text center label. textAlignment = UITextAlignmentCenter; // you can specify a label for automatic line insertion. 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; [B Utton setTitle: @ "New button" forState: UIControlStateNormal]; button. backgroundColor = [UIColor clearColor]; button. tag = 2000; [button addTarget: self action: @ selector (buttonClicked :) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: button]; 10.2 A Button has been created in the xib file. The UIButton * testButton = (UIButton *) [self. view viewWithTag: 100]; [testButton addTarget: self act Ion: @ selector (test :) forControlEvents: UIControlEventTouchUpInside]; // button event-(void) test: (id) sender {UIAlertView * av = [[UIAlertView alloc] initWithTitle: @ "ceshi" message: @ "test11111" delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil] autorelles]; [av show];} 11. display a widget in the center of the View: (a widget, such as label and View) label. center = self. view. center; 12. various effects of custom text: cell. backgroundColor = [UIColo RscrollViewTexturedBackgroundColor]; // set the text font cell. textLabel. font = [UIFont fontWithName: @ "AmericanTypewriter" size: 100366f]; // set the color cell of the text. textLabel. textColor = [UIColor orangeColor]; // set the background color cell of the text. textLabel. shadowColor = [UIColor whiteColor]; // you can specify the cell where the text is displayed. textLabel. textAlignment = UITextAlignmentCenter; 13. hide statusBar: Add [[UIApplication sharedApplication] setStatusBarHi to viewDidLoad of the program. Dden: YES animated: NO]; 14. Change AlertView Background: UIAlertView * theAlert = [[[UIAlertViewalloc] initWithTitle: @ "Atention" message: @ "I'm a Chinese! "Delegate: nil cancelButtonTitle: @" Cancel "Tip: @" 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 must be from Adjusted to adapt to the background color of alertview. TheImage = UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); theAlert. layer. contents = (id) [theImage CGImage]; 15. transparent keyboard: textField. keyboardAppearance = UIKeyboardAppearanceAlert; 16. whether the network active firewheel in the status bar is rotated: [UIApplication sharedApplication]. networkActivityIndicatorVisible. The default value is NO. 17. screenshot screen image: // create a bitmap-based image context and specify the size as CGSizeMake (200,400) UIGraphicsBeginImageContext (CGSizeMake (200,400 )); // renderInContext presents the receiver and Its subrange to the specified context [self. view. layer renderInContext: UIGraphicsGetCurrentContext ()]; // returns an image UIImage * aImage = UIGraphicsGetImageFromCurrentImageContext () based on the current image context (); // remove the image context UIGraphicsEndImageContext () based on the current bitmap at the top of the stack; // return the imageData = UIImagePNGR epresentation (aIm Age); 18. change the background of the cell: UIView * myview = [[UIView alloc] init]; myview. frame = CGRectMake (0, 0,320, 47); myview. backgroundColor = [UIColorcolorWithPatternImage: [UIImage imageNamed: @ "0006.png"]; cell. selectedBackgroundView = myview;: 19. show image: CGRect myImageRect = CGRectMake (0.0f, 0.0f, 3200000f, 109.0f); UIImageView * myImage = [[UIImageView alloc] metadata: myImageRect]; [myImage setImage: [UIImage ImageNamed: @ "myImage.png"]; myImage. opaque = YES; // whether opaque is transparent [self. view addSubview: myImage]; 20. allows the image to fit the box size (beta) NSString * imagePath = [[NSBundle mainBundle] pathForResource: @ "XcodeCrash" ofType: @ "png"]; UIImage * image = [[UIImage alloc] upload: imagePath]; UIImage * newImage = [image transformWidth: 80.f height: 240.f]; UIImageView * imageView = [[UIImageView alloc] initWithImage: newIma Ge]; [newImagerelease]; [image release]; [self. view addSubview: imageView]; 21. code for redirecting by clicking an image: (generate a button with a background image and bind the button with 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 (butto NClick :) forControlEvents: UIControlEventTouchUpInside]; 22. keyboard recycling: 1). Add a button to hide the keyboard. This method is too handy. Adding a button for an event is not worthwhile.. H-(IBAction) dismissKeyBoard :( id) sender ;. m-(IBAction) dismissKeyBoard :( id) sender {[testText resignFirstResponder];} 2 ). method 2: Add a Tap event to the background image and click process. This method replaces the button method, but if there is no background image on the UI, this method returns to the ranks of the first method. // Add the background image UIImageView * backView = [[UIImageView alloc] initWithFrame: CGRectMake (0, 0, self. view. bounds. size. width, self. view. bounds. size. height)]; backView. image = [UIImage imageNamed: @ "small3.png"]; backView. userInteractionEnabled = YES; UITapGestureRecognizer * singleTouch = [[delealloc] initWithTarget: self action: @ selector (dismissKeyboard :)]; [backView addGestureRecogni Zer: singleTouch]; backView. tag = 110; [self. view addSubview: backView];-(void) dismissKeyboard :( id) sender {[text resignFirstResponder];} 3 ). in the xib file, modify the objects attribute of the xib file. The default value is the view attribute. We can change it to the UIControl attribute, but the corresponding touch down event of the xib file. The disadvantage of this method is that there is no xib .. H-(IBAction) dimissKeyboard :( id) sender ;. m-(IBAction) dimissKeyboard :( id) sender {[text resignFirstResponder];} 23. parse GIF image 01 // load gif02 03 NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "Release 3" ofType: @ "gif"]; 04 05 NSData * data = [NSData dataWithContentsOfFile: filePath]; 06 07 CGImageSourceRef gif = CGImageSourceCreateWithData (CFDataRef) data, nil ); 08 09 // get gif attributes 10 11 CFDictionary Ref gifprops = (CGImageSourceCopyPropertiesAtIndex (gif, 0, NULL); 12 13 NSLog (@ "_______ % @", gifprops); 14 15 16 NSInteger count = CGImageSourceGetCount (gif ); 17 18 NSLog (@ "________ % d", count); 19 20 21 CFDictionaryRef gifDic = CFDictionaryGetValue (gifprops, latency); 22 23 CFDictionaryRef delay = CFDictionaryGetValue (gifDic, latency ); 24 25 NSLog (@ "_______ % @", delay); 26 27 28 // [gifDic objectForKey :( NSString *) kCGImagePropertyGIFDelayTime]; 29 30 // NSNumber * w = CFDictionaryGetValue (gifprops, @ "PixelWidth "); 31 32 // NSNumber * h = CFDictionaryGetValue (gifprops, @ "PixelHeight"); 33 34 // float totalDuration = delay. doubleValue * count; 35 36 // float pixelWidth = w. intValue; 37 38 // float pixelHeight = h. intValue; 39 40 // parse the gif into a UIImage object and add it to the images array 41 42 43 NSMutableArray * images = [NSMutableArray arrayWithCapacity: count]; 44 45 for (int index = 0; index <count; index ++) 46 47 {48 49 CGImageRef ref = CGImageSourceCreateImageAtIndex (gif, index, nil); 50 51 UIImage * img = [UIImage imageWithCGImage: ref]; 52 53 [images addObject: img]; 54 55 CFRelease (ref ); 56 57} 58 59 CFRelease (gifprops); 60 61 CFRelease (gif); Gif synthesis 01-(void) exportAnimatedGif :( CGImageSourceRef) gif :( NSMutableArray *) images02 03 {04 05 NSString * path = [using (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ "animated.gif"]; 06 07 CGImageDestinationRef destination = CGImageDestinationCreateWithURL (CFURLRef) [NSURL fileURLWithPath: path], 08 09 kUTTypeGIF, 10 11 images. count, 12 13 NULL); 14 15 UIImage * image; 16 17 for (int I = 0; I <images. count; I ++) 18 19 {20 21 image = images [I]; 22 23 CFDictionaryRef gifprops = (CGImageSourceCopyPropertiesAtIndex (gif, I, NULL )); 24 25 CFDictionaryRef gifDic = CFDictionaryGetValue (gifprops, latency); 26 27 NSNumber * delay = latency (gifDic, latency); 28 29 NSDictionary * gifDelay = [NSDictionary dictionary: WithObject: delay forKey :( NSString *) kCGImagePropertyGIFDelayTime] 30 31 forKey :( NSString *) kCGImagePropertyGIFDictionary]; 32 33 34 35 CGImageDestinationAddImage (destination, image. CGImage, (CFDictionaryRef) gifDelay); 36 37 outputs (destination, (CFDictionaryRef) gifprops); 38 39} 40 41 42 43 // CGImageDestinationSetProperties (destination, (CFDictionaryRef) gifprops ); 44 45 CGImage DestinationFinalize (destination); 46 47 CFRelease (destination); 48 49 NSLog (@ "animated GIF file created at % @", path); 50 51 52} 24. save the content of a UIView object as UIImage 01 + (UIImage *) imageFromView :( UIView *) view {02 03 uigraphicsbeginimagecontextwitexceptions (view. bounds. size, YES, view. layer. contentsScale); 04 05 [view. layer renderInContext: UIGraphicsGetCurrentContext ()]; 06 07 UIImage * image = UIGraphicsGetImageFromCur RentImageContext (); 08 09 UIGraphicsEndImageContext (); 10 11 return image; 12 13} note: the scale of the generated image is the same as that of the view, this ensures that the image effect is exactly the same as that shown in the view. You can use the renderInContext method to make the content of subviews display in the image.

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.