iOS 常用代码整理

来源:互联网 发布:唱粤语歌的男网络歌手 编辑:程序博客网 时间:2024/06/06 13:58
  1. 12.判断邮箱格式是否正确的代码:  
  2. //利用正则表达式验证  
  3.  
  4.     NSString *emailRegex @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
  5.     NSPredicate *emailTest [NSPredicate predicateWithFormat:@"SELF MATCHES%@",emailRegex];  
  6.     return [emailTest evaluateWithObject:email];  
  7.  
  8. 13.图片压缩  
  9. 用法:UIImage *yourImage[self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];  
  10. //压缩图片  
  11. (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize  
  12.  
  13.     // Create graphics image context  
  14.     UIGraphicsBeginImageContext(newSize);  
  15.     // Tell the old image to draw in this newcontext, with the desired  
  16.     // new size  
  17.     [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];  
  18.     // Get the new image from the context  
  19.     UIImage* newImage UIGraphicsGetImageFromCurrentImageContext();  
  20.     // End the context  
  21.     UIGraphicsEndImageContext();  
  22.     // Return the new image.  
  23.     return newImage;  
  24.  
  25. 14.亲测可用的图片上传代码  
  26. (IBAction)uploadButton:(id)sender  
  27.     UIImage *image [UIImage imageNamed:@"1.jpg"]; //图片名  
  28.     NSData *imageData UIImageJPEGRepresentation(image,0.5);//压缩比例  
  29.     NSLog(@"字节数:%i",[imageData length]);  
  30.     // post url  
  31.     NSString *urlString @"http://192.168.1.113:8090/text/UploadServlet";  
  32.     //服务器地址  
  33.     // setting up the request object now  
  34.     NSMutableURLRequest *request [[NSMutableURLRequest alloc] init]  
  35.     [request setURL:[NSURL URLWithString:urlString]];  
  36.     [request setHTTPMethod:@"POST"];  
  37.     //  
  38.     NSString *boundary [NSString stringWithString:@"---------------------------14737809831466499882746641449"];  
  39.     NSString *contentType [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundary];  
  40.     [request addValue:contentType forHTTPHeaderField: @"Content-Type"];  
  41.     //  
  42.     NSMutableData *body [NSMutableData data];  
  43.     [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
  44.     [body appendData:[[NSString stringWithString:@"Content-Disposition:form-data; name="userfile"; filename="2.png"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //上传上去的图片名字  
  45.     [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];  
  46.     [body appendData:[NSData dataWithData:imageData]];  
  47.     [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];  
  48.     [request setHTTPBody:body];  
  49.     // NSLog(@"1-body:%@",body);  
  50.     NSLog(@"2-request:%@",request);  
  51.     NSData *returnData [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  52.     NSString *returnString [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];  
  53.     NSLog(@"3-测试输出:%@",returnString);  
  54.     15.给imageView加载图片  
  55.     UIImage *myImage [UIImage imageNamed:@"1.jpg"];  
  56.     [imageView setImage:myImage];  
  57.     [self.view addSubview:imageView];  
  58.     16.对图库的操作  
  59.     选择相册:  
  60.     UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera 
  61.     if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  
  62.         sourceType=UIImagePickerControllerSourceTypePhotoLibrary 
  63.      
  64.     UIImagePickerController picker [[UIImagePickerControlleralloc]init];  
  65.     picker.delegate self 
  66.     picker.allowsEditing=YES 
  67.     picker.sourceType=sourceType 
  68.     [self presentModalViewController:picker animated:YES];  
  69.     选择完毕:  
  70.     -(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info  
  71.      
  72.         [picker dismissModalViewControllerAnimated:YES];  
  73.         UIImage image=[info objectForKey:UIImagePickerControllerEditedImage];  
  74.         [self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];  
  75.      
  76.     -(void)selectPic:(UIImage*)image  
  77.      
  78.         NSLog(@"image%@",image);  
  79.         imageView [[UIImageView alloc] initWithImage:image];  
  80.         imageView.frame CGRectMake(0, 0, image.size.width, image.size.height);  
  81.         [self.viewaddSubview:imageView];  
  82.         [self performSelectorInBackground:@selector(detect:) withObject:nil];  
  83.      
  84.     detect为自己定义的方法,编辑选取照片后要实现的效果  
  85.     取消选择:  
  86.     -(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker  
  87.      
  88.         [picker dismissModalViewControllerAnimated:YES];  
  89.      
  90.     17.跳到下个View  
  91.     nextWebView [[WEBViewController alloc] initWithNibName:@"WEBViewController" bundle:nil];  
  92.     [self presentModalViewController:nextWebView animated:YES];  
  93.       
  94.       
  95.     //创建一个UIBarButtonItem右边按钮  
  96.     UIBarButtonItem *rightButton [[UIBarButtonItem alloc] initWithTitle:@"右边" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];  
  97.     [self.navigationItem setRightBarButtonItem:rightButton];  
  98.     设置navigationBar隐藏  
  99.     self.navigationController.navigationBarHidden YES;//  
  100.     iOS开发之UIlabel多行文字自动换行 (自动折行)  
  101.     UIView *footerView [[UIView alloc]initWithFrame:CGRectMake(10, 100, 300, 180)];  
  102.     UILabel *label [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 150)];  
  103.     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!";  
  104.     //背景颜色为红色  
  105.     label.backgroundColor [UIColor redColor];  
  106.     //设置字体颜色为白色  
  107.     label.textColor [UIColor whiteColor];  
  108.     //文字居中显示  
  109.     label.textAlignment UITextAlignmentCenter 
  110.     //自动折行设置  
  111.     label.lineBreakMode UILineBreakModeWordWrap 
  112.     label.numberOfLines 0 
  113.     30.代码生成button  
  114.     CGRect frame CGRectMake(0, 400, 72.0, 37.0);  
  115.     UIButton *button [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  116.     button.frame frame 
  117.     [button setTitle:@"新添加的按钮" forState: UIControlStateNormal];  
  118.     button.backgroundColor [UIColor clearColor];  
  119.     button.tag 2000 
  120.     [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];  
  121.     [self.view addSubview:button];  
  122.     31.让某个控件在View的中心位置显示:  
  123.     (某个控件,比如label,View)label.center self.view.center;  
  124.     32.好看的文字处理  
  125.     以tableView中cell的textLabel为例子:  
  126.     cell.backgroundColor [UIColorscrollViewTexturedBackgroundColor];  
  127.     //设置文字的字体  
  128.     cell.textLabel.font [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];  
  129.     //设置文字的颜色  
  130.     cell.textLabel.textColor [UIColor orangeColor];  
  131.     //设置文字的背景颜色  
  132.     cell.textLabel.shadowColor [UIColor whiteColor];  
  133.     //设置文字的显示位置  
  134.     cell.textLabel.textAlignment UITextAlignmentCenter 
  135.     33. ———————-隐藏Status Bar—————————–  
  136.     读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入  
  137.     [[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];  
  138.     33. 更改AlertView背景  
  139.       
  140.     UIAlertView *theAlert [[[UIAlertViewalloc] initWithTitle:@"Atention"  
  141.                                                        message: @"I'm Chinese!"  
  142.                                                       delegate:nil  
  143.                                              cancelButtonTitle:@"Cancel"  
  144.                                              otherButtonTitles:@"Okay",nil] autorelease];  
  145.     [theAlert show];  
  146.     UIImage *theImage [UIImageimageNamed:@"loveChina.png"];  
  147.     theImage [theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];  
  148.     CGSize theSize [theAlert frame].size;  
  149.     UIGraphicsBeginImageContext(theSize);  
  150.     [theImage drawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];//这个地方的大小要自己调整,以适应alertview的背景颜色的大小。  
  151.     theImage UIGraphicsGetImageFromCurrentImageContext();  
  152.     UIGraphicsEndImageContext();  
  153.     theAlert.layer.contents (id)[theImage CGImage];  
  154.     34. 键盘透明  
  155.     textField.keyboardAppearance UIKeyboardAppearanceAlert 
  156.       
  157.     状态栏的网络活动风火轮是否旋转  
  158.     [UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。  
  159.       
  160.     35截取屏幕图片  
  161.     //创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)  
  162.     UIGraphicsBeginImageContext(CGSizeMake(200,400));  
  163.       
  164.     //renderInContext 呈现接受者及其子范围到指定的上下文  
  165.     [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];  
  166.     //返回一个基于当前图形上下文的图片  
  167.     UIImage *aImage UIGraphicsGetImageFromCurrentImageContext();  
  168.     //移除栈顶的基于当前位图的图形上下文  
  169.     UIGraphicsEndImageContext();  
  170.     //以png格式返回指定图片的数据  
  171.     imageData UIImagePNGRepresentation(aImage);  
  172.     36更改cell选中的背景  
  173.     UIView *myview [[UIView alloc] init];  
  174.     myview.frame CGRectMake(0, 0, 320, 47);  
  175.     myview.backgroundColor [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];  
  176.     cell.selectedBackgroundView myview 
  177.     37显示图像:  
  178.     CGRect myImageRect CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);  
  179.     UIImageView *myImage [[UIImageView alloc] initWithFrame:myImageRect];  
  180.     [myImage setImage:[UIImage imageNamed:@"myImage.png"]];  
  181.     myImage.opaque YES//opaque是否透明  
  182.     [self.view addSubview:myImage];  
  183.     38.能让图片适应框的大小(没有确认)  
  184.     NSString*imagePath [[NSBundle mainBundle] pathForResource:@"XcodeCrash"ofType:@"png"];  
  185.     UIImage *image [[UIImage alloc]initWithContentsOfFile:imagePath];  
  186.     UIImage *newImage[image transformWidth:80.f height:240.f];  
  187.     UIImageView *imageView [[UIImageView alloc]initWithImage:newImage];  
  188.     [newImagerelease];  
  189.     [image release];  
  190.     [self.view addSubview:imageView];  
  191.     39.实现点击图片进行跳转的代码:生成一个带有背景图片的button,给button绑定想要的事件!  
  192.     UIButton *imgButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 120, 120)];  
  193.     [imgButton setBackgroundImage:(UIImage *)[self.imgArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];  
  194.     imgButton.tag=[indexPath row];  
  195.     [imgButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; 

转自:jinglijun博客


 

myNetViewController   .h

#import<UIKit/UIKit.h>

#import "myNetconnection.h"

#import "myASIRequest.h"

@interface myNetViewController :UIViewController<myNetconnectionDelegate,myASIRequestDelegate>

{

    NSString *url;

}


@property(nonatomic,retain)myNetconnection* mynetconnetion;

@property(nonatomic,retain)myASIRequest* myasirequest;

@property(nonatomic,retain)UITextView * textview;

@end


myNetViewController    .m

 


//

// myNetViewController.m

//  mytestNet

//

//  Created by rong on13-2-17.

//  Copyright (c)2013 rong. All rights reserved.

//


#import"myNetViewController.h"


@interfacemyNetViewController ()


@end


@implementationmyNetViewController


@synthesizetextview=_textview;

@synthesizemynetconnetion=_mynetconnetion;

-(void)viewDidLoad

{

   [superviewDidLoad];


   // Uncomment the following line topreserve selection between presentations.

   // self.clearsSelectionOnViewWillAppear =NO;

 

   // Uncomment the following line todisplay an Edit button in the navigation bar for this viewcontroller.

   // self.navigationItem.rightBarButtonItem= self.editButtonItem;b

   

   //connection

   UIButton *btnnet=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

   btnnet.frame=CGRectMake(10,20, 130, 30);

   [btnnetsetTitle:@"Connection"forState:UIControlStateNormal];

   [btnnetaddTarget:selfaction:@selector(netAction:)forControlEvents:UIControlEventTouchUpInside];

   [self.viewaddSubview:btnnet];

   

   //ASIHtttprequest

   UIButton *btnasi=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

   btnasi.frame=CGRectMake(150,20, 130, 30);

   [btnasisetTitle:@"ASIHttprequest"forState:UIControlStateNormal];

   [btnasiaddTarget:selfaction:@selector(asiAction:)forControlEvents:UIControlEventTouchUpInside];

   [self.viewaddSubview:btnasi];

   //uitextView

  self.textview=[[UITextViewalloc]initWithFrame:CGRectMake(0,60, 320,400)];

   //self.textview.userInteractionEnabled=NO;

  self.textview.backgroundColor=[UIColorblackColor];

  self.textview.textColor=[UIColorwhiteColor];

   [self.viewaddSubview:self.textview];

   

   //Myconnection

  self.mynetconnetion=[[myNetconnectionalloc]init];

  self.mynetconnetion.delegate=self;

   

  url=@"http://wiapi.hexun.com/news/getlist2.5.php?pid=100234721&pc=20&pn=1&st=0";

   

   //MyAsihttpreques

  self.myasirequest=[[myASIRequestalloc]init];

  self.myasirequest.delegate=self;

   

   

   

}

//connetion Action

-(void)netAction:(id)sender

{

  NSLog(@"netconnection");

  [self.mynetconnetionnetConnectionL:url];

}

-(void)connectionSccess:(NSDictionary*)dic

{

   //NSLog(@"%@",dic);

   self.textview.text=[NSStringstringWithFormat:@"%@",dic];

}


//ASIHttprequest ACtion

-(void)asiAction:(id)sender

{

   //NSLog(@"ASIHttprequest");

   self.textview.text=nil;

   

  [self.myasirequestasiHttprequst:url];

}

-(void)asiHTTPSccess:(NSDictionary*)dic

{

   self.textview.text=[NSStringstringWithFormat:@"%@",dic];

}

-(void)asiHTtpFail:(NSString*)error

{

   self.textview.text=error;

}

-(void)didReceiveMemoryWarning

{

   [superdidReceiveMemoryWarning];

   // Dispose of any resources that can berecreated.

}



- (void)dealloc

{

   [_textviewrelease];

   [_mynetconnetionrelease];

   [super dealloc];

}

 


 


 


 



@end


myASIRequestDelegate   .h

 

#import<Foundation/Foundation.h>

#import "ASIHTTPRequest.h"


@protocol myASIRequestDelegate<NSObject>


- (void)asiHTTPSccess:(NSDictionary *)dic;

- (void )asiHTtpFail:(NSString *)error;


@end



@interface myASIRequest :NSObject<ASIHTTPRequestDelegate>

@property(nonatomic,assign)id<myASIRequestDelegate>delegate;



- (void)asiHttprequst:(NSString *)str;

@end

  
myASIRequest   .m

#import "myASIRequest.h"

#import "XMLReader.h"

@implementation myASIRequest




- (void)asiHttprequst:(NSString *)str

{

    NSURL *url=[NSURL URLWithString:str];

   ASIHTTPRequest * asirequest=[ASIHTTPRequestrequestWithURL:url];

   asirequest.delegate=self;

    [asirequeststartAsynchronous];

    

    

    

    

    

}

-(void)requestFinished:(ASIHTTPRequest*)request

{

   NSDictionary *dic=[XMLReaderdictionaryForXMLData:request.responseDataerror:nil];

   [self.delegateasiHTTPSccess:dic];

    

}

- (void)requestFailed:(ASIHTTPRequest*)request

{

   [self.delegateasiHTtpFail:@"网络请求失败"];

}






- (void)dealloc

{

    

    [superdealloc];

}

@end

myNetconnectionDelegate   .h

#import<Foundation/Foundation.h>


@protocolmyNetconnectionDelegate <NSObject>


- (void)connectionSccess:(NSDictionary * )dic;

- (void)connectionError:(NSError *)error;


@end

@interface myNetconnection : NSObject<NSURLConnectionDataDelegate>

@property (nonatomic,retain)NSMutableData *receiveData;

@property (nonatomic,assign)id<myNetconnectionDelegate> delegate;

- (void)netConnectionL:(NSString *)url;

@end


myNetconnectionDelegate   .m

 

#import"myNetconnection.h"

#import "XMLReader.h"

@implementationmyNetconnection



@synthesizereceiveData=_receiveData;


- (void)netConnectionL:(NSString *)url

{

    NSURL * urll=[NSURLURLWithString:url];

   NSMutableURLRequest *request=[NSMutableURLRequestrequestWithURL:urll cachePolicy:0 timeoutInterval:20.0f];

    [requestsetHTTPMethod:@"POST"];

   [NSURLConnectionconnectionWithRequest:requestdelegate:self];

   

   

}

 - (void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse*)response

{

   self.receiveData=[NSMutableData data];

}

- (void)connection:(NSURLConnection *)connectiondidReceiveData:(NSData *)data

{

    [self.receiveData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

   //仅限于json

 //  NSMutableDictionary *dicc=[NSJSONSerialization JSONObjectWithData:self.receiveDataoptions:NSJSONReadingAllowFragments error:nil];

   NSDictionary* dicc=[XMLReaderdictionaryForXMLData:self.receiveData error:nil];

   

   

   [self.delegateconnectionSccess:dicc];

}

- (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error

{

    [self.delegate connectionError:error];

}

- (void)dealloc

{

   [_receiveData release];

    [super dealloc];

}

@end

原创粉丝点击