常用代码笔记-持续更新

一,蛇型排n格图精灵
//LatticeImage
-(void)LatticeImage:(NSArray *)imageArray_ firstImagePoint:(CGPoint) firstImagePoint_ ColumnStep:(float)ColumnStep_ LineStep:(float)linestep_{

    for(int i=0; i<imageArray_.count;i++) {
        NSString* image=[imageArray_ objectAtIndex:i];
        CCSprite* sprite=[CCSprite spriteWithFile:image];
        int offsetCloum = i%4;
        int offsethLine = i/4;
        sprite.position = ccp(firstImagePoint_.x+ColumnStep_*offsetCloum,firstImagePoint_.y-linestep_*offsethLine);
        [self addChild:sprite];
        
    }

}
调用:
     imageArray=[NSArray arrayWithObjects:@"Icon.png",@"Icon.png",@"Icon.png",@"Icon.png", @"Icon.png",   @"Icon.png",   @"Icon.png",  @"Icon.png",  @"Icon.png",   @"Icon.png",    @"Icon.png", @"Icon.png",  nil];
        
        [self LatticeImage:imageArray firstImagePoint:CGPointMake(360, 680) ColumnStep:180 LineStep:120];
二,数组保存CGpoint
    zhuang_point=ccp(160,246);
    xian_point=ccp(160,246-56);
    xiandui_point=ccp(50,304);
    he_point=ccp(160,304);
    zhuangdui_point=ccp(266,304);
    //数组存post
    NSValue *zhuang_point_va = [NSValue valueWithCGPoint:zhuang_point];
    NSValue *xian_point_va = [NSValue valueWithCGPoint:xian_point];
    NSValue *xiandui_point_va = [NSValue valueWithCGPoint:xiandui_point];
    NSValue *he_point_va = [NSValue valueWithCGPoint:he_point];
    NSValue *zhuangdui_point_va = [NSValue valueWithCGPoint:zhuangdui_point];
    
    mpd =[[MyPostionData alloc]init];
    rect_postion = [NSArray arrayWithObjects:zhuang_point_va,xian_point_va,xiandui_point_va, he_point_va,zhuangdui_point_va,nil];


//        __block void (^blocks)(int); 
//        
//        blocks = ^(int i){ 
//            if(i > 0){ 
//    
//                blocks(i - 1); 
// 
//            } 
//        }; 
//        blocks(3); 
两点差值:
  ccpDistance(<#const CGPoint v1#>, <#const CGPoint v2#>)

双击
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if ([touch tapCount]==2) {
        NSLog(@"双击");
    }
}

改变badgeValue
改变其他viewcontroller 的tabbar 的 badgeValue
UIViewController *tController = [self.tabBarController.viewControllers objectAtIndex:2];
        int     badgeValue = [tController.tabBarItem.badgeValue intValue];
        tController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",badgeValue+1];
如果想改变自己的(一个navigation下的controller)
self.navigationController.tabBarItem.badgeValue = nil

[NSString stringWithFormat:@"Hight: %d°%@   Low: %d°%@", [Temp],@"C",[lTemp],@"C"];

       NSString to NSData:

 NSString* str= @"kilonet";
 NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding]; 

     2. NSDate 用法:

         NSDate  *today;

    NSDate *tomorrow;
    today = [NSDate date];
    tomorrow = [NSDate dateWithTimeInterval:(i*24*60*60) sinceDate:today]; //可能有更好的


         Date format用法:

  -(NSString *) getDay:(NSDate *) d {

    NSString *s ;
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY/MM/dd hh:mm:ss"];
    s = [format stringFromDate:d];
    [format release];
    return s;
}

    各地时区获取:
代码
    NSDate *nowDate = [NSDate new];
    NSDateFormatter *formatter    =  [[NSDateFormatter alloc] init];
    [formatter    setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    //    根据时区名字获取当前时间,如果该时区不存在,默认获取系统当前时区的时间
    //    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Europe/Andorra"];    
    //    [formatter setTimeZone:timeZone];
    //获取所有的时区名字
    NSArray *array = [NSTimeZone knownTimeZoneNames];
    //    NSLog(@"array:%@",array);
    //for循环
    //    for(int i=0;i<[array count];i++)
    //    {
    //        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:[array objectAtIndex:i]];
    //        [formatter setTimeZone:timeZone];
    //        NSString *locationTime = [formatter stringFromDate:nowDate];
    //        NSLog(@"时区名字:%@   : 时区当前时间: %@",[array objectAtIndex:i],locationTime);
    //        //NSLog(@"timezone name is:%@",[array objectAtIndex:i]);
    //    }    
    //快速枚举法
    for(NSString *timeZoneName in array){
        [formatter setTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];
        NSLog(@"%@,%@",timeZoneName,[formatter stringFromDate:nowDate]);
    }

    [formatter release];
    [nowDate release];

     获取毫秒时间:
代码
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    //[dateFormatter setDateFormat:@"hh:mm:ss"]
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSLog(@"Date%@", [dateFormatter stringFromDate:[NSDate date]]);
    [dateFormatter release];

      3. NSCalendar用法:

 -(NSString *) getWeek:(NSDate *) d {


    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *components = [calendar components:units fromDate:d];
    [calendar release];

    switch ([components weekday]) {
        case 2:
            return @"Monday";
            break;
        case 3:
            return @"Tuesday";
            break;
        case 4:
            return @"Wednesday";
            break;
        case 5:
           return @"Thursday";
            break;
        case 6:
            return  @"Friday";
            break;
        case 7:
            return  @"Saturday";
            break;
        case 1:
            return @"Sunday";
            break;
        default:
            return @"No Week";
            break;
    }

    // 用components,我们可以读取其他更多的数据。

}
   4. 用Get方式读取网络数据:

// 将网络数读取为字符串
- (NSString *) getDataByURL:(NSString *) url {
    return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];
}

//读取网络图片
- (UIImage *) getImageByURL:(NSString *) url {
    return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}

     5. 多线程NSThread用法 :

[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];


-(void) scheduleTask {
    //create a pool 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release the pool;
    [pool release];
}

//如果有参数,则这么使用:
[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];


-(void) scheduleTask:(NSDate *) mdate {
    //create a pool 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //release the pool;
    [pool release];
}

//注意selector里有冒号。
    //在线程里运行主线程里的方法 

    [self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];

      6. 定时器NSTimer用法:

代码
  // 一个可以自动关闭的Alert窗口

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                    message:[@"一个可以自动关闭的Alert窗口"
                                                   delegate:nil 
                                          cancelButtonTitle:nil //NSLocalizedString(@"OK", @"OK")   //取消任何按钮
                                          otherButtonTitles:nil];
    //[alert setBounds:CGRectMake(alert.bounds.origin.x, alert.bounds.origin.y, alert.bounds.size.width, alert.bounds.size.height+30.0)];
    [alert show];

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    // Adjust the indicator so it is up a few pixels from the bottom of the alert    
    indicator.center = CGPointMake(alert.bounds.size.width/2,  alert.bounds.size.height-40.0);
    [indicator startAnimating];
    [alert insertSubview:indicator atIndex:0];
    [indicator release];

    [NSTimer scheduledTimerWithTimeInterval:3.0f
                                     target:self
                                   selector:@selector(dismissAlert:)
                                   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert, @"alert", @"testing ", @"key" ,nil]  //如果不用传递参数,那么可以将此项设置为nil.
                                    repeats:NO];

    NSLog(@"release alert");
    [alert release];


-(void) dismissAlert:(NSTimer *)timer{

    NSLog(@"release timer");
    NSLog([[timer userInfo]  objectForKey:@"key"]);

    UIAlertView *alert = [[timer userInfo]  objectForKey:@"alert"];
    [alert dismissWithClickedButtonIndex:0 animated:YES];

}


       定时器停止使用:

        [timer invalidate];
        timer = nil;






     7. 用户缺省值NSUserDefaults读取:

    //得到用户缺省值
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];

    //在缺省值中找到AppleLanguages, 返回值是一个数组
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSLog(@"all language语言 is %@", languages);

    //在得到的数组中的第一个项就是用户的首选语言了
    NSLog(@"首选语言 is %@",[languages objectAtIndex:0]);  



    //get the language & country code
    NSLocale *currentLocale = [NSLocale currentLocale];

    NSLog(@"Language Code is %@", [currentLocale objectForKey:NSLocaleLanguageCode]);    
    NSLog(@"Country Code is %@", [currentLocale objectForKey:NSLocaleCountryCode]);    




     8. View之间切换的动态效果设置:

    SettingsController *settings = [[SettingsController alloc]initWithNibName:@"SettingsView" bundle:nil];
    settings.modalTransiti*****tyle = UIModalTransiti*****tyleFlipHorizontal;  //水平翻转
    [self presentModalViewController:settings animated:YES];
    [settings release];

     9.NSScrollView 滑动用法:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"正在滑动中...");
}

//用户直接滑动NSScrollView,可以看到滑动条
-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

}

// 通过其他控件触发NSScrollView滑动,看不到滑动条
- (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

}
    10. 读取全局的Delegate:


KiloNetAppDelegate *appdelegate = (KiloNetAppDelegate *)[[UIApplication sharedApplication] delegate];
     11.键盘处理系列
 
 //set the UIKeyboard to switch to a different text field when you press return
 
 
//switch textField to the name of your textfield
[textField becomeFirstResponder];
 
 
     12. 半透明层的实现:
 
半透明层
+(void)showWaiting:(UIView *)parent {
    int width = 32, height = 32;
    
    CGRect frame = [parent frame]; //[[UIScreen mainScreen] applicationFrame];
    int x = frame.size.width;
    int y = frame.size.height;
    
    frame = CGRectMake((x - width) / 2, (y - height) / 2, width, height);
    UIActivityIndicatorView* progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];
    [progressInd startAnimating];
    progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    
    
//    frame = CGRectMake((x - 140)/2, (y - height) / 2 + height, 140, 30);
//    UILabel *waitingLable = [[UILabel alloc] initWithFrame:frame];
//    waitingLable.text = @"Proccesing...";
//    waitingLable.textColor = [UIColor whiteColor];
//    waitingLable.font = [UIFont systemFontOfSize:15];
//    waitingLable.backgroundColor = [UIColor clearColor];
    
    frame = [parent frame];
    UIView *theView = [[UIView alloc] initWithFrame:frame];
    theView.backgroundColor = [UIColor blackColor];
    theView.alpha = 0.8;
    
    [theView addSubview:progressInd];
//  [theView addSubview:waitingLable];
    
    [progressInd release];
//    [waitingLable release];
    
    [theView setTag:9999];
    [parent addSubview:theView];
    [theView release];
}
 
+(void)hideWaiting:(UIView *)parent {
    [[parent viewWithTag:9999] removeFromSuperview];
}
  
      13. 设置View的圆角:
 
 // 首先应用  #import <QuartzCore/QuartzCore.h>
 
view.layer.cornerRadius = 10;
view.layer.masksToBounds = YES;
 
  
      14. UIWebView显示本地图片(目前有点问题,无法正确显示图片):
 
代码
    NSString *imagePath = [[NSBundle mainBundle] resourcePath];
    imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
    imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    
    NSLog(@"fileurl=%@",[NSString stringWithFormat:@"file:/%@//",imagePath]);
    
    //[self loadData:[html dataUsingEncoding:NSUTF8StringEncoding] MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"file:/%@//",imagePath]] ];
    [self loadHTMLString:html baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"file:/%@//",imagePath]   ]];
     NSString *path = [[NSBundle mainBundle] bundlePath];
 
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [UIWebView loadHTMLString:html baseURL:baseURL];
    //这段代码可以正确显示图片。
 
 
 
1. 随机数:
srandom(time(NULL)); //随机数种子
 
id d = random(); // 随机数
 
 
  2. 视频播放:
 
    MPMoviePlayerController *moviePlayer;
    moviePlayer = [[MPMoviePlayerController alloc]
                   initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"]]];
    //初始化视频播放器对象,并传入被播放文件的地址
    moviePlayer.movieControlMode = MPMovieControlModeDefault;
    [moviePlayer play];
    //此处有内存溢出
 
 
   3.  启动界面显示:
 
iPhone软件启动后的第一屏图片是非常重要的往往就是loading载入中的意思。设置它说来也简单,但是却无比重要
 
只需要在resource里面将你希望设置的图片更名为Default.png,这个图片就可以成为iPhone载入的缺省图片
 
 
 
    4. iPhone的系统目录:
 
//得到Document目录:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
 
//得到temp临时目录:
NSString *tempPath = NSTemporaryDirectory();
 
//得到目录上的文件地址:
NSString *文件地址 = [目录地址 stringByAppendingPathComponent:@"文件名.扩展名"];
 
 
    5. 状态栏显示Indicator:
 
 
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
 
  6.app Icon显示数字:
 
- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];
}
 
   7.sqlite保存地址:
 
 
代码
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *thePath = [paths objectAtIndex:0];
    NSString *filePath = [thePath stringByAppendingPathComponent:@"kilonet1.sqlite"];
    
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath]
                        stringByAppendingPathComponent:@"kilonet2.sqlite"];  
 
 
  8.Application退出:exit(0);
 
      9. AlertView,Acti*****heet的cancelButton点击事件:
 
代码
-(void) acti*****heet :(UIActi*****heet *) acti*****heet didDismissWithButtonIndex:(NSInteger) buttonIndex {
    NSLog(@"cancel acti*****heet........");
    //当用户按下cancel按钮
    if( buttonIndex == [acti*****heet cancelButtonIndex]) {
        exit(0);
    }
//    //当用户按下destructive按钮
//    if( buttonIndex == [acti*****heet destructiveButtonIndex]) {
//        // DoSomething here.
//    }
}
 
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
     NSLog(@"cancel alertView........");
    if (buttonIndex == [alertView cancelButtonIndex]) {
        exit(0);
    }
} 
    10.给Window设置全局的背景图片:
 
window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"coolblack.png"]];
 
 
    11. UITextField文本框显示及对键盘的控制:
 
代码
#pragma mark -
#pragma mark UITextFieldDelegate 
//控制键盘跳转
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   
    if (textField == _txtAccount) {
        if ([_txtAccount.text length]==0) {
            return NO;
        }
        [_txtPassword becomeFirstResponder];
    } else if (textField == _txtPassword) {
        [_txtPassword resignFirstResponder];
    }
    
    return YES;
}
 
//输入框背景更换
-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{
    
    [textField setBackground:[UIImage imageNamed:@"ctext_field_02.png"]];
    
    return YES;
}
 
-(void) textFieldDidEndEditing:(UITextField *)textField{
    [textField setBackground:[UIImage imageNamed:@"ctext_field_01.png"]];
}
 
 
    12.UITextField文本框前面空白宽度设置以及后面组合按钮设置:
 
代码
    //给文本输入框后面加入空白
    _txtAccount.rightView = _btnDropDown;
    _txtAccount.rightViewMode =  UITextFieldViewModeAlways;
    
    //给文本输入框前面加入空白
    CGRect frame = [_txtAccount frame];
    frame.size.width = 5;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    _txtAccount.leftViewMode = UITextFieldViewModeAlways;
    _txtAccount.leftView = leftview;
 
 
    13. UIScrollView 设置滑动不超出本身范围:
 
 [fcScrollView setBounces:NO]; 
 
     14. 遍历View里面所有的Subview:
 
代码
    NSLog(@"subviews count=%d",[self.view.subviews count]);
    if ([self.view.subviews count] > 0) {
        for (UIView *curView in self.view.subviews) {
                       NSLog(@"view.subviews=%@", [NSString stringWithUTF8String:object_getClassName(curView)]);
        }
    }
 
 
    14. 在drawRect里画文字:
 
     UIFont * f = [UIFont systemFontOfSize:20]; 
 
    [[UIColor darkGrayColor] set]; 
    NSString * text = @"hi \nKiloNet"; 
    [text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];
 
 
    15. NSArray查找是否存在对象时用indexOfObject,如果不存在则返回为NSNotFound.
 
 
 
     16. NString与NSArray之间相互转换:
 
array = [string componentsSeparatedByString:@","];
string = [[array valueForKey:@"description"] componentsJoinedByString:@","];
 
 
     17. TabController随意切换tab bar:
 
[self.tabBarController setSelectedIndex:tabIndex];
 
或者 self.tabBarController.selectedIndex = tabIndex;
 
或者实现下面的delegate来扑捉tab bar的事件: 
 
代码
-(BOOL) tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@"Logout",nil)]) {
        [self showLogout];
        return NO;
    }
    return YES;
}
 
 
 
 
    18. 自定义View之间切换动画:
代码
- (void) pushController: (UIViewController*) controller
         withTransition: (UIViewAnimationTransition) transition
{
    [UIView beginAnimati*****:nil context:NULL];
    [self pushViewController:controller animated:NO];
    [UIView setAnimationDuration:.5];
    [UIView setAnimationBeginsFromCurrentState:YES];        
    [UIView setAnimationTransition:transition forView:self.view cache:YES];
    [UIView commitAnimati*****];
}
    或者:
 
代码
CATransition *transition = [CATransition animation];
transition.duration = kAnimationDuration;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromTop;
transitioning = YES;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
    
self.navigationController.navigationBarHidden = NO;
[self.navigationController pushViewController:tableViewController animated:YES];
 
 
      19. UIWebView加载时白色显示问题解决以及字体统一设置:
 
    uiWebView.opaque = NO; 
 
 代码
 
 
 
     20.计算字符串长度:
 
CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width; 
 
 
 
    21. iTunesLink should be your applicati***** link
 
NSString *iTunesLink = @"http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=xxxxxx&mt=8";
 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
 
 
    22.时间转换NSString & NSDate:
 
 -(NSDate *)NSStringDateT*****Date:(NSString *)string {    
 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [formatter dateFromString:string];
    [formatter release];
    return date;
}
 NSString *year = [myDate descriptionWithCalendarFormat:@"%Y" timeZone:nil locale:nil];
 
 or
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
 
//Optionally for time zone conversti*****
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
 
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
 22。 模拟器的文件位置
 
其中#username#表示当前用户名:
/Users/#username#/Library/Application Support/iPhone Simulator/User/Applicati*****/
 
 
  23.在使用UISearchBar时,将背景色设定为clearColor,或者将translucent设为YES,都不能使背景透明,经过一番研究,发现了一种超级简单和实用的方法:
 
1
[[searchbar.subviews objectAtIndex:0]removeFromSuperview];
背景完全消除了,只剩下搜索框本身了。 
   24.  图像与缓存 :
 
UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
        [UIImage imageNamed:@"icon.png"]]; // 会缓存图片
 
 
 
UIImageView *wallpaper = [[UIImageView alloc] initWithImage:
        [UIImage imageWithContentsOfFile:@"icon.png"]]; // 不会缓存图片 
 
 
 
  25. iphone-常用的对视图图层(layer)的操作
 
对图层的操作:
 
(1.给图层添加背景图片:
myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;
 
(2.将图层的边框设置为圆脚
myWebView.layer.cornerRadius = 8;
myWebView.layer.masksToBounds = YES;
 
(3.给图层添加一个有色边框
myWebView.layer.borderWidth = 5;
myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];
 
 
 
 26. UIPopoverController 使用
 
 
 
-(void) *****etting:(id) sender {
 
    SplitBaseController *detail = [[SettingServerController alloc] init];
 
    
    CGRect frame = [(UIView *)sender frame];
    frame.origin.y = 0;
    
    UIPopoverController *popwin = [[UIPopoverController alloc] initWithContentViewController:detail];
    [popwin setPopoverContentSize:CGSizeMake(400, 300) animated:YES];
    popwin.delegate = self;
    [popwin presentPopoverFromRect: frame inView:self.view permittedArrowDirecti*****:UIPopoverArrowDirectionAny animated:YES];
 
    [detail release];
} 
 
 
 
 27.在UINavigationBar中添加左箭头返回按钮
 
在iPhone里面最讨厌的控件之一就是 UINavigationBar了。这个控件样式修改不方便,连添加按钮也特别麻烦。下面的例子是如何手动添加带箭头的按钮:
 
UINavigationItem *item = [navBar.items objectAtIndex:0];
UINavigationItem *back = [[UINavigationItem alloc] initWithTitle:@"Back"];
NSArray *items = [[NSArray alloc] initWithObjects:back,item,nil];
[navBar setItems:items];
 
- (BOOL)navigationBar:(UINavigationBar *)navigationBar
shouldPopItem:(UINavigationItem *)item{
//在此处添加点击back按钮之后的操作代码 
return NO;
} 
//uilable自动换行
CGSize titleBrandSizeForHeight = [titleBrand.text sizeWithFont:titleBrand.font];
CGSize titleBrandSizeForLines = [titleBrand.text sizeWithFont:titleBrand.font c*****trainedToSize:CGSizeMake(infoWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
titleBrand.numberOfLines = ceil(titleBrandSizeForLines.height/titleBrandSizeForHeight.height);
if (titleBrand.numberOfLines <= 1) {
titleBrand.frame = CGRectMake(5, titleBrand.frame.size.height , infoWidth, titleBrandSizeForHeight.height);
}else {
titleBrand.frame = CGRectMake(5, titleBrand.frame.size.height , infoWidth, titleBrand.numberOfLines*titleBrandSizeForHeight.height);
}


//UIButton 点击事件
       //创建UIButton
     UIButton *sampleButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [sampleButton setFrame:CGRectMake(240,25,60,30)];
    [sampleButton setTitle:@"聊天" forState:UIControlStateNormal];
    [sampleButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
    [sampleButton addTarget:self action:@selector(onBtnClick:) forControlEvents:UIControlEventTouchUpInside];//onBtnClick为方法名称

-(void) onBtnClick:(id)sender
{
   NSLog(@"按钮点击事件");
}

//UIAlertView 输出
     
         UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"提示" 
                              message:@"提示信息" 
                              delegate:self 
                              cancelButtonTitle:@"取消"
                              otherButtonTitles:nil]; //此括号中的属性不可少 cancelButtonTitle属于alert所有按钮中的一个
        
        [alert addButtonWithTitle:@"按钮2"];
        [alert addButtonWithTitle:@"按钮3"];
         
        [alert show];

//弹出窗口按钮的点击事件
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
     
    switch (buttonIndex) {
        case 0:
            NSLog(@"点击取消");
            break;
        case 1:
            NSLog(@"点击创建");
            break;
        case 2:
            NSLog(@"点击搜索");
            break;
    }
    
    [alertView release];
}

消除所有消息
[[UIApplication sharedApplication] cancelAllLocalNotifications];

如何设置UItextfield四个角的弧度

textField.layer.cornerRadius = 9.0;

 

#import <QuartzCore/QuartzCore.h>

任何数字千分分隔
    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:f]];
    return formattedNumberString;


iPhone开发中一些使用小技巧是本文要介绍的内容,与友们分享一篇对编程友人有用的一篇文章,我们来看内容。
经过半年多的iphone开发,我发现在开发过程中最难的就是一些嘈杂的细节,而了解一些小技巧就会达到事半功倍的效果,下面我就总结一下在iphone开发中的一些小技巧。
1、如果在程序中想对某张图片进行处理的话(得到某张图片的一部分)可一用以下代码:
UIImage *image = [UIImage imageNamed:filename];  
CGImageRef imageimageRef = 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” 键以后程序可能并没有退出而是转入了后台运行。如果您想让应用直接退出,最简单的方法是:在 info-plist 里面找到 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种数字键盘才有效果。UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad
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、计算字符串的字数
-(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   
{  
numbernumber = number+0.5;  
}  
}  
return ceil(number);  
}  


键盘透明 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 = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];     cell.selectedBackgroundView = myview;

iPhone键盘改变颜色 只有这2种数字键盘才有效果:UIKeyboardTypeNumberPad,UIKeyboardTypePhonePad keyboardAppearance = UIKeyboardAppearanceAlert 代码如下:

  1.    NSArray *ws = [[UIApplication sharedApplication] windows];
  2.     for(UIView *w in ws){
  3.         NSArray *vs = [w subviews];
  4.         for(UIView *v in vs){
  5.             if([[NSString stringWithUTF8String:object_getClassName(v)] isEqualToString:@"UIKeyboard"]){
  6.                 v.backgroundColor = [UIColor redColor];
  7.             }
  8.         }
  9.     }
从一个界面push到下一界面左上角返回按钮文字设置 在父viewController中如下设置:     UIBarButtonItem *backbutton = [[UIBarButtonItem alloc]init];     backbutton.title = @"返回列表";     self.navigationItem.backBarButtonItem = backbutton;     [backbutton release]; navigationbar的back键触发其他事件 UIButton *back =[[UIButton alloc] initWithFrame:CGRectMake(200, 25, 63, 30)]; [back addTarget:self act ion:@selector(reloadRowData:) forControlEvents:UIControlEventTouchUpInside]; [back setImage:[UIImage imageNamed:@"返回按钮.png"] forState:UIControlStateNormal]; UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:back]; self.navigationItem.leftBarButtonItem = loginButtonItem [back release]; [backButtonItem release]; 防止屏幕暗掉锁屏 [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; 将图片从左到右翻页效果显示         UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 470)];     [imageView setImage:[UIImage imageNamed:@"Bg.jpg"]];     self.myImageView =imageView;     [self.view addSubview:imageView];     [imageView release];     CGContextRef context = UIGraphicsGetCurrentContext();     [UIView beginAnimations:nil context:context];     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];     [UIView setAnimationDuration:0.5];     [myImageView setFrame:CGRectMake(0, 0, 310, 470)];        [UIView commitAnimations]; 让覆盖在下面层的视图接受触摸事件 searchImage.exclusiveTouch = YES;//第一层 searchImage.userInteractionEnabled = NO; myMapView.exclusiveTouch = NO;//第二层 myMapView.userInteractionEnabled = YES; View的缩放 NSValue *touchPointValue = [[NSValue valueWithCGPoint:CGPointMake(100,100)] retain]; [UIView beginAnimations:nil context:touchPointValue]; transform = CGAffineTransformMakeScale(0.1,0.21); firstPieceView.transform = transform; [UIView commitAnimations];   cocos2d动作完成后执行的方法 用CCCallFunc 实现应该可以 id action=[CCCallFunc actionWithTarget:self selector:@selector(setFlikX:)]; - (void) setFlikX:(id) sender {     [sprite setFlipX:YES];  }

设置游戏速度

  1. [[CCScheduler sharedScheduler] setTimeScale:XX];   

这里的XX仍然是倍率:传入1表示原速,大于1表示增快,小于1表示放慢速度~

精灵定义好z值后,修改z值

 [self reorderChild:kai_pai z:18];

UItableView 横向滚动

CGRect tableViewRect =CGRectMake(0.0,0.0,50.0,320.0);     self.tableView =[[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStylePlain];     tableView.center =CGPointMake(self.view.frame.size.width /2,self.view.frame.size.height /2);     tableView.delegate=self;     tableView.dataSource =self;     //tableview逆时针旋转90度。         tableView.transform =CGAffineTransformMakeRotation(-M_PI /2);       // scrollbar 不显示     tableView.showsVerticalScrollIndicator = NO;

 

==============================================================================================

(UITableViewCell*)tableViewUITableView*)aTableView cellForRowAtIndexPathNSIndexPath*)indexPath {

    UITableViewCell*cell;    cell =[tableView dequeueReusableCellWithIdentifier:@"identifier"];    if(cell ==nil){                 cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle                                reuseIdentifier@"identifier"] autorelease];         // cell顺时针旋转90度        cell.contentView.transform =CGAffineTransformMakeRotation(M_PI /2);   }        return cell; }

得到用户的首选语言

NSUserDefaults* defs =[NSUserDefaults standardUserDefautls];//得到用户缺省值  NSArray* languages =[defs objectForKey:@"AppleLanguages"];//在缺省值中找到AppleLanguages, 返回值是一个数组  NSString* preferredLang =[languages objectAtIndex:0];//在得到的数组中的第一个项就是用户的首选语言了

判断设备总结

1234567891011//可通过苹果review + (NSString*)getDeviceVersion {     size_t size;     sysctlbyname("hw.machine", NULL, &size, NULL, 0);     char*machine = (char*)malloc(size);     sysctlbyname("hw.machine", machine, &size, NULL, 0);     NSString*platform = [NSStringstringWithCString:machine encoding:NSUTF8StringEncoding];     free(machine);     returnplatform; } 输出: //@"iPad1,1" //@"iPad2,1" //@"i386" 逗号后面数字解释:(i386是指模拟器) 1-WiFi版 2-GSM/WCDMA 3G版 3-CDMA版 AppleTV(2G) (AppleTV2,1) iPad (iPad1,1) iPad2,1 (iPad2,1)Wifi版 iPad2,2 (iPad2,2)GSM3G版 iPad2,3 (iPad2,3)CDMA3G版 iPhone (iPhone1,1) iPhone3G (iPhone1,2) iPhone3GS (iPhone2,1) iPhone4 (iPhone3,1) iPhone4(vz) (iPhone3,3)iPhone4 CDMA版 iPhone4S (iPhone4,1) iPodTouch(1G) (iPod1,1) iPodTouch(2G) (iPod2,1) iPodTouch(3G) (iPod3,1) iPodTouch(4G) (iPod4,1) 另外放两个固件下载地址: http://apple.178.com/ios/ http://ipad.sj.91.com/ios/ 判断ipad/iphone

UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone

或者

[[[UIDevice currentDevice] model] isEqualToString:@"iPad"];

判断设备是否有摄像头

[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]; iphone xcode4.2 如何修改项目工程名称 执行如下操作:view-->Utilities-->Show File Inspector  然后在右边的identity tab下的Project Name修改项目名称。

phone 使用Safari打开网页 .

  1. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.websitename.com"]];
  2. Objective-C 字符串去除空格、换行符

     

    ObjC的每个NSString对象,均有一个 stringByTrimmingCharactersInSet 方法。这个方法接受的参数为 NSCharactersInSet 对象。

    NSCharactersInSet 对象只有两个方法:whitespaceCharacterSet 和 whitespaceAndNewlineCharacterSet。前者仅去除空格;后者不仅去除空格,也会去除换行符。

    NSString *str = @" 前 有 空 格,后 有 换 行 符! "; 

    NSString *trimStr = [str stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

Phone 判断输入得邮箱是否合法

BOOL NSStringIsValidEmail(NSString *checkString)   {       NString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";       NSString *laxString = @".+@.+\.[A-Za-z]{2}[A-Za-z]*";       NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;       NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];      return [emailTest evaluateWithObject:checkString];   }
2秒后执行方法

  [self performSelector:@selector(addShrinkImg) withObject:self afterDelay:2.0f];
  
cocos2d 贞动画   
 CGSize winSize = [CCDirector sharedDirector].winSize;
    
    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"skymenus01-07_default.plist"];
    
    CCSprite* _storyImage1=[CCSprite spriteWithSpriteFrameName:@"010001.png"];
    
    [_storyImage1 setPosition:ccp(winSize.width/2, winSize.height/2)];
    
    [self addChild:_storyImage1];
    
    NSMutableArray *walkAnimFrames = [NSMutableArray array];
  
    for( int i=1;i<9;i++)
        
    {
        
        [walkAnimFrames addObject:
         
         [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
          
        [NSString stringWithFormat:@"01000%d.png", i]]];

    }
    
    CCAnimation* animation = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];
    
// 执行一下调用结束方法
//    id action1 = [CCSequence actions:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO],[CCCallFuncN actionWithTarget:self selector:@selector(startGameScene)], nil];
    id action1 = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO]];
  
    [_storyImage1 runAction:action1];

常用代码整理:



  
  
12. 判断邮箱格式是否正确的代码:
// 利用正则表达式验证
-( 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];
}
13. 图片压缩
用法: 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;
}
14. 亲测可用的图片上传代码
- ( 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 alloc ] init ] ;
[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 alloc ] initWithData :returnData encoding : NSUTF8StringEncoding ];
NSLog ( @"3- 测试输出: %@" ,returnString);
15. imageView 加载图片
UIImage *myImage = [ UIImage imageNamed : @"1.jpg" ];
   [ imageView setImage :myImage];
   [ self . view addSubview : imageView ];
16. 对图库的操作
选择相册:
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];
}
17. 跳到下个 View
nextWebView = [[ WEBViewController alloc ] initWithNibName : @"WEBViewController" bundle : nil ];
[ self presentModalViewController : nextWebView animated : YES ];
// 创建一个 UIBarButtonItem 右边按钮
UIBarButtonItem *rightButton = [[ UIBarButtonItem alloc ] initWithTitle : @" 右边 " style : UIBarButtonItemStyleDone target : self action : @selector (clickRightButton)];
[ self . navigationItem setRightBarButtonItem :rightButton];
设置 navigationBar 隐藏
self . navigationController . navigationBarHidden = YES ;//
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;
30. 代码生成button
CGRect frame = CGRectMake ( 0 , 400 , 72.0 , 37.0 );
UIButton *button = [ UIButton buttonWithType : UIButtonTypeRoundedRect ];
button. frame = frame;
[button setTitle : @" 新添加的按钮 " forState: UIControlStateNormal ];
button. backgroundColor = [ UIColor clearColor ];
button. tag = 2000 ;
[button addTarget : self action : @selector (buttonClicked:) forControlEvents : UIControlEventTouchUpInside ];
[ self . view addSubview :button];
31. 让某个控件在 View 的中心位置显示:
(某个控件,比如 label View label . center = self . view . center ;
32.好看的文字处理
tableView cell textLabel 为例子:
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;
33. ———————-隐藏Status Bar—————————– 读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];
33. 更改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];
34. 键盘透明 textField.keyboardAppearance = UIKeyboardAppearanceAlert; 状态栏的网络活动风火轮是否旋转 [UIApplication sharedApplication].networkActivityIndicatorVisible 默认值是 NO 35 截取屏幕图片 // 创建一个基于位 图的图形上下文并指定大小为CGSizeMake(200,400) UIGraphicsBeginImageContext(CGSizeMake(200,400));  //renderInContext 呈现接受者及其子范围到 指定的上下文 [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];     // 返回 一个基于当前图形上下文的图片  UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();   // 移除栈顶 的基于当前位图的图形上下文 UIGraphicsEndImageContext(); // png 格式 返回指定图片的数据 imageData = UIImagePNGR epresentation(aImage); 36 更改cell 选中 的背景     UIView *myview = [[UIView alloc] init];     myview.frame = CGRectMake(0, 0, 320, 47);     myview.backgroundColor = [UIColorcolorWithPatternImage:[UIImage imageNamed:@"0006.png"]];     cell.selectedBackgroundView = myview; 
37 显示 图像: CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);  UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; [myImage setImage:[UIImage imageNamed:@"myImage.png"]];  myImage.opaque = YES; //opaque 是否透明 [self.view addSubview:myImage];
38. 能让图片适应框的大小(没有确认)
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];
39. 实现点击图片进行跳转的代码:生成一个带有背景图片的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]; cocos2d加载gif         UIWebView* web = [[UIWebView alloc]initWithFrame:CGRectMake(-8, -8, 560,600)];         //固定图片         [(UIScrollView *)[[web subviews] objectAtIndex:0] setBounces:NO];                  NSString* gifFileName = @"Icon.png";                  NSMutableString* htmlStr = [NSMutableString string];                  [htmlStr appendString:@"<p><img src=\""];                  [htmlStr appendFormat:@"%@",gifFileName];                  [htmlStr appendString:@"\" alt=\"picture\"/>"];                  [web loadHTMLString:htmlStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];           [[[CCDirector sharedDirector]openGLView]addSubview:web]; ,,,单双击判断     switch (makelove_) {         case 0:             [self.navigationController setNavigationBarHidden:YES];             makelove_ =1;             break;         case 1:             [self.navigationController setNavigationBarHidden:NO];             makelove_ =0;             break;                      default:             break;     } 数组存在一个元素      array_num = [[NSArray alloc]initWithObjects:@"I",@"II",@"III",@"IV",@"V", nil];          [array_num containsObject:@"i"]; ******************输出bool   NSLog(@"%@",switch1[0].on?@"YES":@"NO"); 1,在线程中更新ui,精灵     [NSThread detachNewThreadSelector:@selector(updateProcess) toTarget:self withObject:nil];          return self; } -(void)updateProcess{       NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];          sleep(10);          [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];          [p release]; } -(void)updateUI{     NSLog(@"this is run");     CCSprite* demo = [CCSprite spriteWithFile:@"Icon.png"];     demo.position = ccp(200,200);     [self addChild:demo]; }      //得到IMEI值         NSString *myImie=[[UIDevice currentDevice] uniqueIdentifier];
 强制横竖屏:[[CCDirector sharedDirector] setDeviceOrientation:kCCDeviceOrientationLandscapeRight];

空精灵ccColor4B boardColor = ccc4(59, 203, 237, 128);

        CCLayerColor * ground = [CCLayerColor layerWithColor:boardColor width:3152 height:768];

        ground.anchorPoint = CGPointZero;

        ground.position = CGPointZero;

画一个圆

-(void)intiUIOfView

{

    UIBezierPath *path=[UIBezierPath bezierPath];

    

    CGRect rect=[UIScreen mainScreen].applicationFrame;

    

    [path addArcWithCenter:CGPointMake(rect.size.width/2,rect.size.height/2-20) radius:100 startAngle:0 endAngle:2*M_PI clockwise:NO];

    arcLayer=[CAShapeLayer layer];

    arcLayer.path=path.CGPath;//46,169,230

    arcLayer.fillColor=[UIColor clearColor].CGColor;

    arcLayer.strokeColor=[UIColor colorWithWhite:2 alpha:0.7].CGColor;

    arcLayer.lineWidth=5;

    arcLayer.frame=self.view.frame;

    [self.view.layer addSublayer:arcLayer];

    [self drawLineAnimation:arcLayer];

    

    

}

-(void)drawLineAnimation:(CALayer*)layer

{

    CABasicAnimation *bas=[CABasicAnimation animationWithKeyPath:@"strokeEnd"];

    bas.duration=10;

    bas.delegate=self;

    bas.fromValue=[NSNumber numberWithInteger:0];

    bas.toValue=[NSNumber numberWithInteger:1];

    [layer addAnimation:bas forKey:@"key"];

}






  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值