iOS开发中一些小功能代码(持续更新)

--判断邮箱格式是否正确的代码:
//利用正则表达式验证
-(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];
}
 //正则判断电话
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以13, 15,18开头,八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

--图片压缩
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;
}
 
--给imageView加载图片
UIImage *myImage = [UIImage imageNamed:@"1.jpg"];
   [imageView setImage:myImage];
   [self.view addSubview:imageView];
 
--对图库的操作
选择相册:
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];
}

--创建一个UIBarButton右边按钮
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右边" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
[self.navigationItem setRightBarButtonItem:rightButton];
 
--UIlabel多行文字自动换行 (自动折行)
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;
 
--让某个控件在View的中心位置显示:
(某个控件,比如label,View)<span style="font-family: 宋体;">label.center = self.view.center;</span>

--隐藏statusBar:
在程序的viewDidLoad中加入
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];
注:iOS 7之后会再plist文件中加入一条View controller-based status bar appearance 的描述,并设置为YES,才能进行代码操作。
 
--更改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];

--键盘透明:
textField.keyboardAppearance = UIKeyboardAppearanceAlert;

--.状态栏的网络活动风火轮是否旋转:
[UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。
 
--截取屏幕图片:
//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)
UIGraphicsBeginImageContext(CGSizeMake(200,400)); 

//renderInContext 呈现接受者及其子范围到指定的上下文
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    //返回一个基于当前图形上下文的图片
 UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
  //移除栈顶的基于当前位图的图形上下文
UIGraphicsEndImageContext();
//以png格式返回指定图片的数据
imageData = UIImagePNGRepresentation(aImage);

--更改cell选中的背景:
    
UIView *myview = [[UIView alloc] init];
    myview.frame = CGRectMake(0, 0, 320, 47);
    myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
    cell.selectedBackgroundView = myview;

--能让图片适应框的大小(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];
 
--实现点击图片进行跳转的代码:(生成一个带有背景图片的button,给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];
 或者在图片上添加一个手势点击事件,并讲图片的userInteractionEnabled设置为YES
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    image.userInteractionEnabled = YES;
    [self.view addSubview:image];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doAct:)];
    [image addGestureRecognizer:tapGesture];

--键盘回收:
    //点击键盘以外的地方隐藏键盘
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyBoard)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];

--延时函数: 

[NSThread sleepForTimeInterval:3];
     [self performSelector:@selector(machineBallAction) withObject:nil afterDelay:0];


--实现随机数:

srandom(time(NULL));

--我们通过发送消息给对象出发特定动作;对象发送某些变化的时候通过回调函数(callback)通知我们。对象在特定事件发生的时候,就会调用对应的回调函数,触发业务逻辑。
     回调函数通过所谓的代理(Delegation)来实现.

     delegate使用方法:

     @property (assign) <id>xxxDelegate delegate;

     正确的使用方法是使用assign属性而不是retain。

     之所以对于delegate这类对象使用assign而不是用retain是为了防止循环retain(retain loop)。
     具体原因请移至:http://www.cnblogs.com/kimimaro/archive/2011/09/05/2167576.html

编程习惯:定义Bool类型值时,@property(nonatomic,getter=isSoundOn) BOOL soundOn;


--手动创建内存自动释放池:

       NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc]init];

       // TODO

       // 向对象发送一条autorelese消息时,就将该对象加入到自己手动创建的内存释放池中。在此方法结束时调用[pool release],将释放添加到该内存池的所有对象.

       [pool release];

       // 如若在自动释放池pool 调用release方法之后,某对象的retainCount不为0,该对象将继续保持可用。

--任何基本数据类型(包括char数据类型),可以通过使用NSNumber类根据这些数据类型来创建对象。

  1. NSNumber *myNumber, *floatNubmer;  
  2.   
  3. // long value  
  4. myNumber = [NSNumber numberWithLong:0xabcdef];  
  5. NSLog(@"%lx",[myNumber longValue]);          // 输出:abcdef  
  6.   
  7. // char value  
  8. myNumber = [NSNumber numberWithChar:'X'];  
  9. NSLog(@"%c", [myNumber charValue]);          // 输出:X  
  10.   
  11. // float value  
  12. floatNubmer = [NSNumber numberWithFloat:100.00];  
  13. NSLog(@"%g",[floatNubmer floatValue]);       // 输出:100  


--当把某一个对象以AddObject或者初始化的形式加入到Array,Dictionary中时,该对象retainCount将+1。

     当把某一个对象以remover的形式从Array,Dictionary移除时,该对象retainCount将-1。

     当使用copy 和mutableCopy 产生数组副本时,数组中每个元素的保持计数将+1。


--异常:exc_bad_access.

       引用对象已经释放,即“魔鬼引用”。与VS中的“未将引用的对象应用到对象的实例”类似。


--更新UITableView数据问题:

        采用Sqlite3轻量级数据库来存储数据,通过调试发现,数据库中数据已更新,但UITableView并没有更新。

        解决方法:performSelectorOnMainThread:@selector(reloaddata) withObject:nil waitUntilDone:YES

                 但datasource并没有数据,需要重新加载数据。



 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值