常见比较实用的代码

来源:互联网 发布:淘宝网商城汽车配件 编辑:程序博客网 时间:2024/05/29 04:31
1.判断邮箱格式是否正确的代码:
//利用正则表达式验证
-(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.图片压缩
用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];
//压缩图片
- (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.亲测可用的图片上传代码
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"]; //图片名
NSData *imageData = UIImageJPEGRepresentation(image,0.5);//压缩比例
NSLog(@"字节数:%i",[imageData length]);
// post url
NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet";
//服务器地址
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest allocinit] ;
[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]]; //上传上去的图片名字
[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 allocinitWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"3-测试输出:%@",returnString);


4.对图库的操作
选择相册:
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];
选择完毕:
 -(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为自己定义的方法,编辑选取照片后要实现的效果
取消选择:
 -(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
   [picker dismissModalViewControllerAnimated:YES];
}


5.iOS开发之UIlabel多行文字自动换行 自动折行
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!";
//背景颜色为红色
label.backgroundColor = [UIColor redColor];
//设置字体颜色为白色
label.textColor = [UIColor whiteColor];
//文字居中显示
label.textAlignment = UITextAlignmentCenter;
//自动折行设置
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;


6.好看的文字处理
tableViewcelltextLabel为例子:
cell.backgroundColor = [UIColorscrollViewTexturedBackgroundColor];
//
设置文字的字体
cell.textLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:100.0f];
//
设置文字的颜色
cell.textLabel.textColor = [UIColor orangeColor];
//
设置文字的背景颜色
cell.textLabel.shadowColor = [UIColor whiteColor];
//
设置文字的显示位置
cell.textLabel.textAlignment = UITextAlignmentCenter;


7. ———————-隐藏Status Bar—————————–
读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];



8. 更改AlertView背景 
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)];//这个地方的大小要自己调整,以适应alertview的背景颜色的大小。
   theImage = UIGraphicsGetImageFromCurrentImageContext();   
UIGraphicsEndImageContext();

   theAlert.layer.contents = (id)[theImage CGImage];



9. 键盘透明
textField.keyboardAppearance = UIKeyboardAppearanceAlert;


10.状态栏的网络活动风火轮是否旋转
[UIApplication sharedApplication].networkActivityIndicatorVisible
默认值是NO

11.截取屏幕图片
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400)); 
//renderInContext 
呈现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    //
返回一个基于当前图形上下文的图片
 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
  //
移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();
//
png格式返回指定图片的数据
imageData = UIImagePNGR
epresentation(aImage);


12.身份证号码判断

-(BOOL)isCrediCard:(NSString *)IDNumb

{

    //判断位数

    if ([IDNumblength] !=15 && [IDNumblength] !=18)

    {

        returnNO;

    }

    NSString *carid = IDNumb;

    long lSumQT =0;

    //加权因子

    int R[] ={7,9,10,5,8,4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

    //校验码

    unsigned char sChecker[11]={'1','0','X','9','8','7','6','5','4','3','2'};

    //15位身份证号转换成18

    NSMutableString *mString = [NSMutableStringstringWithString:IDNumb];

    

    if ([IDNumblength] ==15)

    {

        [mString insertString:@"19"atIndex:6];

        long p =0;

        const char *pid = [mString UTF8String];

        

        for (int i=0; i<=16; i++)

        {

            p += (pid[i]-48) * R[i];

        }

        int o = p%11;

        

        NSString *string_content = [NSStringstringWithFormat:@"%c",sChecker[o]];

        [mString insertString:string_contentatIndex:[mStringlength]];

        carid = mString;

    }

    //判断地区码

    NSString * sProvince = [caridsubstringToIndex:2];

    

    if (![selfareaCode:sProvince])

    {

        returnNO;

    }

    //判断年月日是否有效

    //年份

    int strYear = [[selfgetStringWithRange:caridValue1:6Value2:4]intValue];

    //月份

    int strMonth = [[selfgetStringWithRange:caridValue1:10Value2:2]intValue];

    //

    int strDay = [[selfgetStringWithRange:caridValue1:12Value2:2]intValue];

    

    NSTimeZone *localZone = [NSTimeZonelocalTimeZone];

    NSDateFormatter *dateFormatter = [[NSDateFormatteralloc]init];

    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    [dateFormatter setTimeZone:localZone];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date=[dateFormatterdateFromString:[NSStringstringWithFormat:@"%d-%d-%d 12:01:01",strYear,strMonth,strDay]];

    

    if (date ==nil)

    {

        returnNO;

    }

    

    const char *PaperId  = [carid UTF8String];

    //检验长度

    if( 18 != strlen(PaperId)) return -1;

    //校验数字

    for (int i=0; i<18; i++)

    {

        if ( !isdigit(PaperId[i]) && !(('X' == PaperId[i] ||'x' == PaperId[i]) &&17 == i) )

        {

            returnNO;

        }

    }

    //验证最末的校验码

    for (int i=0; i<=16; i++)

    {

        lSumQT += (PaperId[i]-48) * R[i];

    }

    

    if (sChecker[lSumQT%11] != PaperId[17] )

    {

        returnNO;

    }

    returnYES;

}

-(BOOL)areaCode:(NSString *)code

{

    NSMutableDictionary *dic = [[NSMutableDictionaryalloc]init];

    [dic setObject:@"北京"forKey:@"11"];

    [dic setObject:@"天津"forKey:@"12"];

    [dic setObject:@"河北"forKey:@"13"];

    [dic setObject:@"山西"forKey:@"14"];

    [dic setObject:@"内蒙古" forKey:@"15"];

    [dic setObject:@"辽宁"forKey:@"21"];

    [dic setObject:@"吉林"forKey:@"22"];

    [dic setObject:@"黑龙江" forKey:@"23"];

    [dic setObject:@"上海"forKey:@"31"];

    [dic setObject:@"江苏"forKey:@"32"];

    [dic setObject:@"浙江"forKey:@"33"];

    [dic setObject:@"安徽"forKey:@"34"];

    [dic setObject:@"福建"forKey:@"35"];

    [dic setObject:@"江西"forKey:@"36"];

    [dic setObject:@"山东"forKey:@"37"];

    [dic setObject:@"河南"forKey:@"41"];

    [dic setObject:@"湖北"forKey:@"42"];

    [dic setObject:@"湖南"forKey:@"43"];

    [dic setObject:@"广东"forKey:@"44"];

    [dic setObject:@"广西"forKey:@"45"];

    [dic setObject:@"海南"forKey:@"46"];

    [dic setObject:@"重庆"forKey:@"50"];

    [dic setObject:@"四川"forKey:@"51"];

    [dic setObject:@"贵州"forKey:@"52"];

    [dic setObject:@"云南"forKey:@"53"];

    [dic setObject:@"西藏"forKey:@"54"];

    [dic setObject:@"陕西"forKey:@"61"];

    [dic setObject:@"甘肃"forKey:@"62"];

    [dic setObject:@"青海"forKey:@"63"];

    [dic setObject:@"宁夏"forKey:@"64"];

    [dic setObject:@"新疆"forKey:@"65"];

    [dic setObject:@"台湾"forKey:@"71"];

    [dic setObject:@"香港"forKey:@"81"];

    [dic setObject:@"澳门"forKey:@"82"];

    [dic setObject:@"国外"forKey:@"91"];

    

    if ([dic objectForKey:code] == nil)

    {

        returnNO;

    }

    returnYES;

}

-(NSString *)getStringWithRange:(NSString *)str Value1:(NSInteger )value1 Value2:(NSInteger )value2;

{

    return [strsubstringWithRange:NSMakeRange(value1,value2)];

}


13.正则判断手机号码地址格式

+(BOOL)isMobileNumber:(NSString *)mobileNum

{

    /**

     * 手机号码

     * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188

     * 联通:130,131,132,152,155,156,185,186

     * 电信:133,1349,153,180,189

     */

    NSString * MOBILE =@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";

    /**

     10         * 中国移动:China Mobile

     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188

     12         */

    NSString * CM =@"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";

    /**

     15         * 中国联通:China Unicom

     16         * 130,131,132,152,155,156,185,186

     17         */

    NSString * CU =@"^1(3[0-2]|5[256]|8[56])\\d{8}$";

    /**

     20         * 中国电信:China Telecom

     21         * 133,1349,153,180,189

     22         */

    NSString * CT =@"^1((33|53|8[09])[0-9]|349)\\d{7}$";

    /**

     25         * 大陆地区固话及小灵通

     26         * 区号:010,020,021,022,023,024,025,027,028,029

     27         * 号码:七位或八位

     28         */

    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";

    

    NSPredicate *regextestmobile = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", MOBILE];

    NSPredicate *regextestcm = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CM];

    NSPredicate *regextestcu = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CU];

    NSPredicate *regextestct = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", CT];

    

    if (([regextestmobileevaluateWithObject:mobileNum] ==YES)

        || ([regextestcm evaluateWithObject:mobileNum] == YES)

        || ([regextestct evaluateWithObject:mobileNum] == YES)

        || ([regextestcu evaluateWithObject:mobileNum] == YES))

    {

        returnYES;

    }

    else

    {

        returnNO;

    }

}


14.判断是否是纯数字

+ (BOOL)isNumText:(NSString *)str{

    NSString * regex        =@"(/^[0-9]*$/)";

    NSPredicate * pred      = [NSPredicatepredicateWithFormat:@"SELF MATCHES %@", regex];

    BOOL isMatch            = [predevaluateWithObject:str];

    if (isMatch) {

        returnYES;

    }else{

        returnNO;

    }

}


0 0
原创粉丝点击