【IOS】iPhone开发技巧&cocos2d(更新中...)

--------------------------------------------------------------

开发技巧

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 alloc] initWithCGImage:imageRefRect];

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

#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : 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];

}

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

#import <QuartzCore/QuartzCore.h>
UIGraphicsBeginImageContext(currentView.bounds.size);     //currentView 当前的view
[currentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

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

    UILocalNotification *notification=[[UILocalNotification alloc] init];
    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];

6、捕获iphone通话事件:

CTCallCenter *center = [[CTCallCenter alloc] init];
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 alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];
imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

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

CGRect frame = {{0, 0}, {320, 20}};
UIWindow* wd = [[UIWindow alloc] initWithFrame:frame];
[wd setBackgroundColor:[UIColor clearColor]];
[wd setWindowLevel:UIWindowLevelStatusBar];
frame = CGRectMake(100, 0, 30, 20);
UIImageView* img = [[UIImageView alloc] initWithFrame: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];

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 alloc] initWithFormat:@"tel://%@",number]; //number为号码字符串     
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]]; //拨号 
        
    }

12、更改iphone的键盘颜色:

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

2. keyboardAppearance  UIKeyboardAppearanceAlert 

    
    - (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];
                    
                }
                
            }
            
        }

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

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

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

16、计算字符串的字数

    -(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);      
    }

--------------------------------------------------------------

cocos2d-iphone(v2.1,xcode5.0)

1.添加cocos2d-iphone模板到xcode中

在终端用下述命令添加模板到xcode中: sudo path/install-templates.sh -f  
说明1:其中,sudo 为获取root权限,path为cocos2d路径+解压后的文件名,-f表示覆盖已经存在的cocos2d模板。
说明2:如果已经或去过root权限,再次添加模板不用添加 sudo。添加也无所谓,终端会有错误提示,再改就是,嘿嘿!~

2.利用cocos2d-iphone模板创建应用之后,编译成功但无法运行

问题描述:用最基础的cocos2d模板创建项目之后,编译成功,但是无法运行,提示“choose a destination with a supported architecture in order to run on this device. xcode 5”。
网上也有类似错误,解决方法包括:检查项目文件名是否有空格;检查app所需系统版本是否高于Xcode能运行的版本;但是这些问题在楼主的新建项目中都不存在。

问题解决:最后决定,先跳过运行这一步,直接“convert project to ARC”。然后,提示有19个错误,检查之后发现都是,创建自动释放池,id前加*,或者使用了被弃用的方法。
转换之后,再点击运行,终于看到helloword界面。虽然对着mac本本有四个月,而第一次使用xcode也是一年前的事了,但是始终都对mac和xoce心存畏惧,唉,要抓紧时间了。

3.新建项目,按照书上对Cocos2d项目支持ARC的步骤进行,最后编译时报错

问题描述:

Ld /Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Products/Debug-iphonesimulator/HelloWord2.app/HelloWord2 normal i386
    cd /Users/marong/project/Cocos2d/HelloWord2
    setenv IPHONEOS_DEPLOYMENT_TARGET 6.1
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.0.sdk -L/Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Products/Debug-iphonesimulator -F/Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Products/Debug-iphonesimulator -filelist /Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Intermediates/HelloWord2.build/Debug-iphonesimulator/HelloWord2.build/Objects-normal/i386/HelloWord2.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -lz -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=6.1 -lcocos2d-library -framework OpenAL -framework UIKit -framework QuartzCore -framework AVFoundation -framework CoreGraphics -framework OpenGLES -framework Foundation -framework AudioToolbox -Xlinker -dependency_info -Xlinker /Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Intermediates/HelloWord2.build/Debug-iphonesimulator/HelloWord2.build/Objects-normal/i386/HelloWord2_dependency_info.dat -o /Users/marong/Library/Developer/Xcode/DerivedData/HelloWord2-ddijqbonjxfttwbhiexrtaphvgfq/Build/Products/Debug-iphonesimulator/HelloWord2.app/HelloWord2

ld: library not found for -lcocos2d-library
clang: error: linker command failed with exit code 1 (use -v to see invocation)

感觉应该是sdk的版本不对。运行在模拟器中给定的是7.0的版本,但是项目要求的是6.1。到网上搜了一下 添加旧sdk版本到xcode中的方法。

copy the iPhoneOS5.1.sdk to the directory 
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk

and iPhoneSimulator5.1.sdk to
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk

问题解决:明天早上继续。。。

--------------------------------------------------------------

你可能感兴趣的:(【IOS】iPhone开发技巧&cocos2d(更新中...))