iPhone开发技巧

来源:互联网 发布:iso8859 java 编辑:程序博客网 时间:2024/06/04 17:39
原文地址。
1、如果在程序中想对某张图片进行处理的话(得到某张图片的一部分)可一用以下代码:

UIImage *image = [UIImage imageNamed:filename];

CGImageRef imageRef = image.CGImage;

CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);

CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);

UIImage *imageRect = [[UIImage allocinitWithCGImage:imageRefRect];

===================学习补充个

截取给定View返回image (当前看到的视图的image)

- (UIImage *)captureWithView:(UIView *) view
{
    if(version7)
    {
        UIGraphicsBeginImageContext(view.frame.size);
    }
    else
    {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque,0.0);

//在ios7中不执行 不会报错但是界面就卡在那边 找了很久才找到问题的根源 这个方法截取的图片会比上一个清晰 但是IOS7中不能执行了 只能用上面一个方法
    }
    [view.layerrenderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

2、判断设备是iphone还是iphone4的代码:


640*960 3.5寸 为iPhone4

#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640960), [[UIScreen mainScreen] currentMode].size) : NO)


640*960 4寸 为iPhone5

//判断是否为4寸设备设备

#define inch4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640,1136), [[UIScreen mainScreen] currentMode].size) : NO)


版本号判断

//是否为7.0以上的的设备

#define version7 ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0 ? YES:NO)



3、判断邮箱输入的是否正确:


- (BOOL) validateEmail: (NSString *) candidate

{

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:candidate];

}

强大的NSPredicete 大家可以看看这个 

 http://blog.sina.com.cn/s/blog_859ab336010158dz.html


4、如何把当前的视图作为照片保存到相册中去:

 

#import <QuartzCore/QuartzCore.h>

UIGraphicsBeginImageContext(currentView.bounds.size);     //currentView 当前的view

[currentView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage, nilnilnil);

 = = 上面自己添加了.....

5、本地通知(类似于push通知)按home键到后台 十秒后触发:

UILocalNotification *notification=[[UILocalNotification allocinit]; 

if (notification!=nil) { 

NSLog(@">> support local notification"); 

NSDate *now=[NSDate new]; 

notification.fireDate=[now addTimeInterval:10]; 

notification.timeZone=[NSTimeZone defaultTimeZone]; 

notification.alertBody=@"该去吃晚饭了!"

[[UIApplication sharedApplication].scheduleLocalNotification:notification];

}

又是个不懂的东西

电脑编译有问题 有些函数已经弃用了

UILocalNotification *notification=[[UILocalNotificationalloc]init];

    if (notification!=nil)

    {

        NSDate *now=[NSDatedate];

        notification.fireDate=[now dateByAddingTimeInterval:5];   //5秒后推送

        notification.timeZone=[NSTimeZonedefaultTimeZone];

        notification.repeatInterval = kCFCalendarUnitWeek;

        notification.alertBody=@"该去吃晚饭了!";

        notification.alertAction = @"打开";

       // notification.hasAction = YES;

        notification.applicationIconBadgeNumber =1;       //应用上的红色提示数字   application.applicationIconBadgeNumber = 0;原来那个数字提示是这样改的

        notification.soundName =UILocalNotificationDefaultSoundName;

        [[UIApplicationsharedApplication]scheduleLocalNotification:notification];

    }

改过之后的效果

参考: http://www.cnblogs.com/bandy/archive/2012/03/29/2423555.html


6、捕获iphone通话事件:

CTCallCenter *center = [[CTCallCenter allocinit];

center.callEventHandler = ^(CTCall *call//有个块的用法

{

NSLog(@"call:%@"call.callState);

}


7、iOS 4 引入了多任务支持,所以用户按下 “Home” 键以后程序可能并没有退出而是转入了后台运行。如果您想让应用直接退出,最简单的方法是:在 infoplist 里面找到 Application does not run in background 一项,勾选即可。


8、使UIimageView的图像旋转:


float rotateAngle = M_PI;

CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);

imageView.transform = transform;


9、设置旋转的原点:

 

#import <QuartzCore/QuartzCore.h>

UIImageView *imageView = [[UIImageView allocinitWithImage:[UIImage imageNamed:@"bg.png"]];

imageView.layer.anchorPoint = CGPointMake(0.51.0);


++++++++++   更改图片的锚点

self.imageV.frame = cgrectmake(-160,150,320,160);

self.imageV.layer.anchorPoint =CGPointMake(0,0.5);

 //设置锚点的时候旋转的中心点没有变是改变了图片的位置 默认锚点为(0.50.5

//让图片在屏幕的左边旋转 以前不懂 将图片加在两倍imageV宽的View 中 选中view达到那种效果 现在设置锚点就可以了 个人理解 一张图片大小位置确定后 图片的旋转的中心点就确定了 这时改变锚点是该片图片的layer相对这个锚点的位置 

frame.origin.x = center.x - anchorPoint.x * bounds.size.width/2.0;//上面的imageV的layer的_x变为0
frame.origin.y = center.y - anchorPoint.x * bounds.size.height/2.0;//上面的imageV的layer的_y没有变
frame.size = bounds.size;大小不变

可以看看这个:http://blog.csdn.net/ch_soft/article/details/8199251

可以试试让他转转....

10、实现自定义的状态栏(遮盖状态栏):

CGRect frame = {{00}, {32020}};//好吧 frame还可以这样写 学习了 笨啊

UIWindow* wd = [[UIWindow allocinitWithFrame:frame];

[wd setBackgroundColor:[UIColor clearColor]];

[wd setWindowLevel:UIWindowLevelStatusBar];

frame = CGRectMake(10003020);

UIImageView* img = [[UIImageView allocinitWithFrame:frame];

[img setContentMode:UIViewContentModeCenter];

[img setImage:[UIImage imageNamed:@"00_0103.png"]];

[wd addSubview:img];

[wd makeKeyAndVisible];


[UIView beginAnimations:nil context:nil];

[UIView setAnimationDuration:2];

frame.origin.x += 150;

[img setFrame:frame];

[UIView commitAnimations];


= =试验过 上面那样写不可以 找了好久 终于找到问题的根源 UIWidow 要定义成变量 或者 属性 不能是临时的 不然不能显示 


11、在程序中实现电话的拨打:


//添加电话图标按钮 

UIButton *btnPhone = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; 

btnPhone.frame = CGRectMake(280,10,30,30); 

UIImage *image = [UIImage imageNamed:@"phone.png"];     

[btnPhone setBackgroundImage:image forState:UIControlStateNormal]; 


//点击拨号按钮直接拨号 

[btnPhone addTarget:self action:@selector(callAction:event:)forControlEvents:UIControlEventTouchUpInside]; 


[cell.contentView addSubview:btnPhone];  //cell是一个UITableViewCell 


//定义点击拨号按钮时的操作 

- (void)callAction:(id)sender event:(id)event{ 

NSSet *touches = [event allTouches]; 

UITouch *touch = [touches anyObject]; 

CGPoint currentTouchPosition = [touch locationInView:self.listTable]; 

NSIndexPath *indexPath = [self.listTable indexPathForRowAtPoint: currentTouchPosition]; 

if (indexPath == nil) { 

return

NSInteger section = [indexPath section]; 

NSUInteger row = [indexPath row]; 

NSDictionary *rowData = [datas objectAtIndex:row]; 

 

NSString *num = [[NSString allocinitWithFormat:@"tel://%@",number]; //number为号码字符串     

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //拨号 

}

= =说了一堆只有最后两句话有用 疼 建议大家看看这个 : http://blog.sina.com.cn/s/blog_65a8ab5d01017nlg.html

NSString *number =@"号码可以填自己的号码实验";

 NSString *num = [[NSString alloc] initWithFormat:@"tel://%@",number]; //number为号码字符串如果使用这个方法结束电话之后会进入联系人列表

 NSString *num = [[NSStringalloc]initWithFormat:@"telprompt://%@",number];//而这个方法则打电话前先弹框 是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核

这里面有很多自己没做的和不知道的东西 等下下面把工程文件传上来共享大笑


12、更改iphone的键盘颜色:


1.只有这2种数字键盘才有效果。UIKeyboardTypeNumberPadUIKeyboardTypePhonePad

2. keyboardAppearance  UIKeyboardAppearanceAler

- (void)textViewDidBeginEditing:(UITextView *)textView{

NSArray *ws = [[UIApplication sharedApplication] windows];

for(UIView *w in ws){

NSArray *vs = [w subviews];

for(UIView *v in vs)

{

if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"])

{

v.backgroundColor = [UIColor redColor];

}

}

}

= = 靠 又折腾了很久  这个颜色设置对uitextField无效 而且关键字也不是UIKeyboard 大家不行的话 用

UIPeripheralHostView 试试 这个键盘设置在uitextview上才能设置


13、设置时区


NSTimeZone *defaultTimeZone = [NSTimeZone defaultTimeZone];

NSTimeZone *tzGMT = [NSTimeZone timeZoneWithName:@"GMT"];

[NSTimeZone setDefaultTimeZone:tzGMT];

上面两个时区任意用一个。


14、Ipad隐藏键盘的同时触发方法。

 

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(keyboardWillHide:)

name:UIKeyboardWillHideNotification

  object:nil];


- (IBAction)keyboardWillHide:(NSNotification *)note//键盘的监听方法


14、在一个程序中打开另一个程序的方法。

 

http://www.cocoachina.com/iphonedev/sdk/2010/0322/768.html

15、计算字符串的字数

-(int)calculateTextNumber:(NSString *)text

{

float number = 0.0;

int index = 0;

for (index; index < [text length]; index++)

{

NSString *protoText = [text substringToIndex:[text length] - index];

NSString *toChangetext = [text substringToIndex:[text length] -1 -index];

NSString *charater;

if ([toChangetext length]==0)

{

charater = protoText;

}

else 

{

NSRange range = [text rangeOfString:toChangetext];

charater = [protoText stringByReplacingCharactersInRange:range withString:@""];

 

}

NSLog(charater);

if ([charater lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)

{

number++;

}

else 

{

number = number+0.5;

}

}

return ceil(number);

} 

练习的工程文件下载地址戳这里..........

原创粉丝点击