Key code integration in iOS development
1. Code to determine whether the email format is correct:
// Use regular expressions 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 evaluateWithObject: email];
}
2. Image Compression
Usage: UIImage * yourImage = [self imageWithImageSimple: image scaledToSize: CGSizeMake (210.0, 210.0)]; // compressed image-(UIImage *) imageWithImageSimple :( UIImage *) image scaledToSize :( CGSize) newSize
{
// Create a graphics image context UIGraphicsBeginImageContext (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 context UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
// End the context UIGraphicsEndImageContext ();
// 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 (@" number of bytes: % I ", [imageData length]);
// Post url NSString * urlString = @ "http: // 192.168.1.113: 8090/text/UploadServlet ";
// Server address // setting up the request object now NSMutableURLRequest * 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]; // The 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 images to imageView
UIImage * myImage = [UIImage imageNamed: @ "1.jpg"];
[ImageView setImage: myImage];
[Self. view addSubview: imageView];
5. operations on the Image Library
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];
Select:-(void) imagePickerController :( UIImagePickerController *) pickerdidFinishPickingMediaWithInfo :( NSDictionary *) info
{
[Picker dismissModalViewControllerAnimated: YES];
UIImage * image = [info objectForKey: UIImagePickerControllerEditedImage];
[Self defined mselector: @ 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 validate mselectorinbackground: @ selector (detect :) withObject: nil];
}
Detect is a custom method. After editing and selecting a photo, unselect the effect:-(void) imagePickerControllerDIdCancel :( UIImagePickerController *) picker
{
[Picker dismissModalViewControllerAnimated: YES];
}
6. jump to the next View
NextWebView = [[WEBViewController alloc] initWithNibName: @ "WEBViewController" bundle: nil];
[Self presentModalViewController: nextWebView animated: YES];
7. Create a button on the Right of 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. navigationBarHidden = YES ;//
9. UIlabel multi-Line 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 Button
CGRect frame = CGRectMake (0,400, 72.0, 37.0 );
UIButton * button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
Button. frame = frame;
[Button setTitle: @ "New button" forState: UIControlStateNormal];
Button. backgroundColor = [UIColor clearColor];
Buttons. 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 and obtained through the tag
UIButton * testButton = (UIButton *) [self. view viewWithTag: 100];
[TestButton addTarget: self action: @ selector (test :) forControlEvents: UIControlEventTouchUpInside];
// Button event
-(Void) test: (id) sender {
UIAlertView * av = [[[UIAlertView alloc] initWithTitle: @ "ceshi" message: @ "test11111" delegate: nil cancelButtonTitle: @ "OK" failed: nil] autorelease];
[Av show];
}
11. display a widget in the center of the View:
(A control, such as label and View) label. center = self. view. center;
12. Various effects of custom text:
Cell. backgroundColor = [UIColorscrollViewTexturedBackgroundColor];
// Set the text font
Cell. textLabel. font = [UIFont fontWithName: @ "AmericanTypewriter" size: 100366f];
// Set the text color
Cell. textLabel. textColor = [UIColor orangeColor];
// Set the background color of the text
Cell. textLabel. shadowColor = [UIColor whiteColor];
// Set the text display position
Cell. textLabel. textAlignment = UITextAlignmentCenter;
13. Hide statusBar:
Add it to 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: 0 topCapHeight: 0];
CGSize theSize = [theAlert frame]. size;
UIGraphicsBeginImageContext (theSize );
[TheImage drawInRect: CGRectMake (5, 5, theSize. width-10, theSize. height-20)]; // adjust the size of this place 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 tornado wheel 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 based on the current image context.
UIImage * aImage = UIGraphicsGetImageFromCurrentImageContext ();
// Remove the image context at the top of the stack based on the current bitmap
UIGraphicsEndImageContext ();
// Return the data of the specified image in png format
ImageData = UIImagePNGR epresentation (aImage );
18. Change the background of the cell:
UIView * myview = [[UIView alloc] init];
Myview. frame = cgrecctmake (0, 0,320, 47 );
Myview. backgroundColor = [UIColorcolorWithPatternImage: [UIImage imageNamed: @ "0006.png"];
Cell. selectedBackgroundView = myview ;:
19. Show Images:
CGRect myImageRect = CGRectMake (0.0f, 0.0f, 3200000f, 109.0f );
UIImageView * myImage = [[UIImageView alloc] initWithFrame: myImageRect];
[MyImage setImage: [UIImage imageNamed: @ "myImage.png"];
MyImage. opaque = YES; // whether opaque is transparent
[Self. view addSubview: myImage];
20. Adapt the image to the 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. Code for clicking images to jump:(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 (buttonClick :) forControlEvents: UIControlEventTouchUpInside];
22. keyboard recycling:
1) Add a button to hide the keyboard with the touch down event. 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 a background image with processing time
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 = [[UITapGestureRecognizer alloc] initWithTarget: self action: @ selector (dismissKeyboard :)];
[BackView addGestureRecognizer: 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 xib is no longer a tragedy.
. H
-(IBAction) dimissKeyboard :( id) sender;
. M
-(IBAction) dimissKeyboard :( id) sender {
[Text resignFirstResponder];
}
23. GIF Image Parsing
// Load gif
02
03 NSString * filePath = [[NSBundle mainBundle] pathForResource: @ "prop 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 CFDictionaryRef 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, kCGImagePropertyGIFDictionary );
22
23 CFDictionaryRef delay = CFDictionaryGetValue (gifDic, kCGImagePropertyGIFDelayTime );
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
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
-(Void) exportAnimatedGif :( CGImageSourceRef) gif :( NSMutableArray *) images
02
03 {
04
05 NSString * path = [[NSSearchPathForDirectoriesInDomains (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
18
19 {
20
21 image = images [I];
22
23 CFDictionaryRef gifprops = (CGImageSourceCopyPropertiesAtIndex (gif, I, NULL ));
24
25 CFDictionaryRef gifDic = CFDictionaryGetValue (gifprops, kCGImagePropertyGIFDictionary );
26
27 NSNumber * delay = CFDictionaryGetValue (gifDic, kCGImagePropertyGIFDelayTime );
28
29 NSDictionary * gifDelay = [NSDictionary dictionaryWithObject: [NSDictionary dictionaryWithObject: delay forKey :( NSString *) kCGImagePropertyGIFDelayTime]
30
31 forKey :( NSString *) kCGImagePropertyGIFDictionary];
32
33
34
35 CGImageDestinationAddImage (destination, image. CGImage, (CFDictionaryRef) gifDelay );
36
37 CGImageDestinationSetProperties (destination, (CFDictionaryRef) gifprops );
38
39}
40
41
42
43 // CGImageDestinationSetProperties (destination, (CFDictionaryRef) gifprops );
44
45 CGImageDestinationFinalize (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
+ (UIImage *) imageFromView :( UIView *) view {
02
03 uigraphicsbeginimagecontextwitexceptions (view. bounds. size, YES, view. layer. contentsScale );
04
05 [view. layer renderInContext: UIGraphicsGetCurrentContext ()];
06
07 UIImage * image = UIGraphicsGetImageFromCurrentImageContext ();
08
09 UIGraphicsEndImageContext ();
10
11 return image;
12
13}
Note: the scale of the generated image is the same as that of the view, so that the image effect and view display are consistent, you can use the renderInContext method to display the content of subviews.