常用代码

来源:互联网 发布:mysql增加字段 编辑:程序博客网 时间:2024/05/16 23:34



1,获取翻转事件,并开启翻转:

只要在viewcontroller的类中加入

 


-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{


//翻转后要执行的代码


return YES;


}



2,-(void)viewWillAppear:(BOOL)animated,-(void)viewDidLoad 的区别。

viewwillappear是每次视图控制器的视图出现前执行的代码。而viewdidload是每次视图控制器载入是执行的代码。

比如说:当a视图控制器的视图第一次出现是两个都要执行,但当a被push后有pop回来时,只有viewwillappear执行。

 

 

3,如何让视图始终跟着手指移动,并有反弹事件

 

xsum=photopositon.origin.x+photopositon.size.width/2-touchstart.x;

ysum=photopositon.origin.y+photopositon.size.height/2-touchstart.y;

currentview.center=CGPointMake(xsum+p.x,ysum+p.y);

if (pow(currentview.center.x-160,2.0)>pow(photopositon.size.width/2,2.0)||

pow(currentview.center.y-240,2.0)>pow(photopositon.size.height/2, 2.0)) 

{

[UIView beginAnimations:nil context:NULL];

[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

[UIView setAnimationDuration:0.3];

currentview.center=CGPointMake(160, 240);

[UIView commitAnimations];

}

 

就是让currentview的视图中心始终与手指保持一定的方位。

 

4,控制导航条和toolbar

 

[self.navigationController  ...]

 

[self.navigationController.toolbar  ...]

比如说让他们都消失:

 

[self.navigationController setToolbarItems:NULL animated:YES];

[self.navigationController.toolbar setBarStyle:UIBarStyleBlackTranslucent];

[self.navigationController setToolbarHidden:NO animated:YES];

 

 

5,自定义控件事件:

addTarget:self action:@selector(....) forControlEvents:....

比如获取某个按钮的触摸事件;

 

[new addTarget:self action:@selector(onChooseItem:) forControlEvents:UIControlEventTouchUpInside]

 

则当按钮按下时,- (void)onChooseItem:(id)sender 就会被调用。

sender传的就是被按下按钮的指针。

 

6.获取文件的路径,即获取documents的路径

   //获取文件路径

    NSArray*path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString*documentsPath=[path objectAtIndex:0];


NSLog(@"%@",documentsPath);

补充:


1.NSSearchPathForDirectoriesInDomains和NSHomeDirectory

    iPhone和symbian3rd一样,会为每一个应用程序生成一个私有目录,这个目录位于/Users/sundfsun2009/Library/ApplicationSupport/iPhone       Simulator/User/Applications下,并随即生成一个数字字母串作为目录名,在每一次应用程序启动时,这个字母数字串都是不同于上一次。


   通常使用Documents目录进行数据持久化的保存,而这个Documents目录可以通过NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserdomainMask,YES)得到,代码如下:


    NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString*documentsDirectory = [paths objectAtIndex:0];


   // NSString *path= [documentsDirectorystringByAppendingPathComponent:@"aa.plist"];


   NSLog(@"path:  %@",path);


    打印结果如下:


    path:  /Users/apple/Library/Application Support/iPhoneSimulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/Documents


    而这个目录还可以通过NSHomeDirectory()来得到,代码如下:


    NSString*destPath = NSHomeDirectory();

   NSLog(@"path:  %@",destPath);

   //destPath = [destPathstringByAppendingPathComponent: @"Documents"];

    //NSString*xmlpath = [destPath stringByAppendingPathComponent:@"menu/menu.xml"];


    打印结果如下:


    path:  /Users/apple/Library/Application Support/iPhoneSimulator/4.2/Applications/6F4BC466-C5D6-440C-BAAC-BE20FA468C61


   看看两者打印出来的结果,我们可以看出这两种方法的不同。


2. 浏览document下所有图片资源


    #define DOCUMENTS_FOLDER [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]

    NSArray*fileList = [[[NSFileManager defaultManager]directoryContentsAtPath:DOCUMENTS_FOLDER]

             pathsMatchingExtensions:[NSArray arrayWithObject:@"png"]] ;


3. 得到图片中的某一部分:


    UIImage *image= [UIImage imageNamed:filename];

    CGImageRefimageRef = image.CGImage;


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


    CGImageRefimageRefRect = CGImageCreateWithImageInRect(imageRef, rect);


    UIImage*imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];



 


7.在documents的路径下创建文件。

首先要获取documents的路径,如上第6条。

其次就是下面的语句了:

NSString *writePath=[NSStringstringWithFormat:@"%@/%@.txt",documentsPath,@"aaa"];

NSData *data = [@""dataUsingEncoding:NSUTF8StringEncoding];//新文件的初始数据,设为空

[[NSFileManager defaultManager]createFileAtPath:writePath contents:dataattributes:nil];//创建文件的命令在这里

这样就可以在documents文件夹下创建一个aaa.txt的文件了。哈哈哈哈哈。

或者是用下面的语句,

NSString *writePath=[NSStringstringWithFormat:@"%@/%@.txt",documentsDirectory,@"bbb"];

NSError *error;

[@"fasdfasdasddaa"writeToFile:writePath atomically:YES encoding:NSUTF8StringEncodingerror:&error];

这样就可以在documents文件夹下创建一个bbb.txt的文件了。并且,文件中的有"fasdfasdasddaa"字符。

总结起来就是,先给要存储的东西取一个名字,然后,找到它的路径。然后以这个名字创建。创建的时候可以添加内容。

当然,图片也可以批量的生成,假如说让你把一张图片复制500遍,并且给他按照(1-500)重命名。

你可以用上面的方法,用一个循环批量的生成500张图片。

 


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

    NSData *data =UIImagePNGRepresentation(image);

    NSString*documentPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];

    NSMutableArray*muArray;

    NSString*filePath = nil;

    for (int j = 1; j<=500; j++) {

       filePath = [[NSString alloc]initWithFormat:@"%@/%d.png",documentPath,j];

       [data writeToFile:filePathatomically:YES];

       NSString *newPath =[[NSString alloc] initWithFormat:@"%@",documentPath];

       muArray = [[NSMutableArrayalloc] initWithContentsOfFile:newPath];

       [muArrayaddObject:filePath];

       [filePath release];



7.iphone开发中随机数的产生。

 


// Get random number between 0 and99 

int x = arc4random() %81

// Get random number between 500 and999 

int y =((arc4random()%501)+500);


NSLog(@"0--99之间的随机数%d",x);

NSLog(@"500--999之间的随机数%d",y);



8.好看的文字处理

以tableView中cell的textLabel为例子:


   cell.backgroundColor  = [UIColorscrollViewTexturedBackgroundColor];

   //设置文字的字体

   cell.textLabel.font = [UIFont fontWithName:@"American Typewriter" size:100.0f];

   //设置文字的颜色

   cell.textLabel.textColor = [UIColor orangeColor];

   //设置文字的背景颜色

   cell.textLabel.shadowColor = [UIColor whiteColor];

   //设置文字的显示位置

   cell.textLabel.textAlignment = UITextAlignmentCenter;


9.新手学习webview


//Web view

//A basic UIWebView. 


CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0); 

UIWebView *webView = [[UIWebView alloc]initWithFrame:webFrame]; 

[webView setBackgroundColor:[UIColorwhiteColor]]; 

NSString *urlAddress = @"http://www.google.com"

NSURL *url = [NSURL URLWithString:urlAddress];

NSURLRequest *requestObj = [NSURLRequestrequestWithURL:url]; 

[webView loadRequest:requestObj];

[self addSubview:webView]; 

[webView release]




10。———————-隐藏StatusBar—————————–
读者可能知道一个简易的方法,那就是在程序的viewDidLoad中加入

[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];

 

11.更改AlertView背景   

 

 UIAlertView *theAlert =[[[UIAlertViewalloc] initWithTitle:@"Atention"

                                               message: @"I'm aChinese!"

                                             delegate:nil 

                                      cancelButtonTitle:@"Cancel" 

                                      otherButtonTitles:@"Okay",nil] autorelease];

    [theAlertshow];

    UIImage*theImage = [UIImage imageNamed:@"loveChina.png"];   

    theImage =[theImage stretchableImageWithLeftCapWidth:0topCapHeight:0];

    CGSize theSize= [theAlert frame].size;

   

   UIGraphicsBeginImageContext(theSize);   

    [theImagedrawInRect:CGRectMake(5, 5, theSize.width-10, theSize.height-20)];//这个地方的大小要自己调整,以适应alertview的背景颜色的大小。

    theImage =UIGraphicsGetImageFromCurrentImageContext();   

   UIGraphicsEndImageContext();

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

 

 

12。iOS后台播放声音  

 

AVAudioSession *session = [AVAudioSessionsharedInstance];  

    [sessionsetActive:YES error:nil];  

    [sessionsetCategory:AVAudioSessionCategoryPlayback error:nil];

 

13。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

UITextInputTraits属性 autocapitalizationType           设置键盘自动大小写的属性    UITextAutocapitalizationTypeNone autocorrectionType property 设置是否有自动修改提示  UITextAutocorrectionTypeNoenablesReturnKeyAutomatically  Boolean值-设置在用户没有输入是returnKey禁用,默认值NOkeyboardAppearance 设置键盘显示方式  除了默认模式 还有一个UIKeyboardAppearanceAlert模式keyboardType              设置键盘类型   UIKeyboardTypePhonePad等returnKeyType             设置renturnKey按键上的提示文字    UIReturnKeyGo  UIReturnKeyNextsecureTextEntry           BOOL值 -- 设置是否是密码保护模式输入如下:设置登录用的 输入框 UITextField用户名输入框:m_TF_username =[[UITextField alloc]initWithFrame:my_frame];m_TF_username.borderStyle =UITextBorderStyleNone;m_TF_username.clearButtonMode =UITextFieldViewModeWhileEditing;m_TF_username.delegate =self;m_TF_username.returnKeyType =UIReturnKeyNext;m_TF_username.autocapitalizationType =UITextAutocapitalizationTypeNone;[m_TF_usernamebecomeFirstResponder];密码输入框:m_TF_password = [[UITextField alloc]initWithFrame:my_frame];m_TF_password.borderStyle =UITextBorderStyleNone;m_TF_password.clearButtonMode =UITextFieldViewModeWhileEditing;m_TF_password.delegate =self;m_TF_password.returnKeyType =UIReturnKeyGo;m_TF_password.secureTextEntry =YES;键盘透明textField.keyboardAppearance= UIKeyboardAppearanceAlert;状态栏的网络活动风火轮是否旋转[UIApplicationsharedApplication].networkActivityIndicatorVisible,默认值是NO。截取屏幕图片//创建一个基于位图的图形上下文并指定大小为CGSizeMake(200,400)UIGraphicsBeginImageContext(CGSizeMake(200,400)); //renderInContext呈现接受者及其子范围到指定的上下文[self.view.layerrenderInContext: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:[UIImageimageNamed:@"0006.png"]];   cell.selectedBackgroundView = myview; 在数字键盘上添加button://定义一个消息中心[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];//addObserver:注册一个观察员 name:消息名称-(void)keyboardWillShow:(NSNotification *)note{    // createcustom button   UIButton *doneButton = [UIButtonbuttonWithType:UIButtonTypeCustom];   doneButton.frame = CGRectMake(0, 163, 106,53);   [doneButton setImage:[UIImage imageNamed:@"5.png"]forState:UIControlStateNormal];   [doneButton addTarget:self action:@selector(addRadixPoint)forControlEvents:UIControlEventTouchUpInside];       // locate keyboardview   UIWindow* tempWindow = [[[UIApplication sharedApplication] windows]objectAtIndex:1];//返回应用程序window   UIView*keyboard;   for(int i=0; i<[tempWindow.subviews count]; i++)//遍历window上的所有subview         keyboard =[tempWindow.subviewsobjectAtIndex:i];       // keyboardview found; add the custom button toit      if([[keyboard description] hasPrefix:@"正则表达式使用:被用于正则表达式的字串必须是可变长的,不然会出问题将一个空间放在视图之上[scrollView insertSubview:searchButtonaboveSubview:scrollView];从本地加载图片NSString*boundle = [[NSBundle mainBundle] resourcePath];[web1loadHTMLString:[NSString stringWithFormat:@"常用代码"] baseURL:[NSURLfileURLWithPath:boundle]];从网页加载图片并让图片在规定长宽中缩小[cell.img loadHTMLString:[NSStringstringWithFormat:@"

常用代码",goodsInfo.GoodsImg]baseURL:nil];将网页加载到webview上通过javascript获取里面的数据,如果只是发送了一个连接请求获取到源码以后可以用正则表达式进行获取数据NSString*javaScript1 =@"document.getElementsByName('.u').item(0).value";NSString*javaScript2 =@"document.getElementsByName('.challenge').item(0).value";NSString*strResult1 = [NSString stringWithString:[theWebViewstringByEvaluatingJavaScriptFromString:javaScript1]];NSString*strResult2 = [NSString stringWithString:[theWebViewstringByEvaluatingJavaScriptFromString:javaScript2]];用NSString怎么把UTF8转换成unicodeutf8Str //NSString*unicodeStr = [NSString stringWithCString:[utf8Str UTF8String]encoding:NSUnicodeStringEncoding];View自己调用自己的方法:[selfperformSelector:@selector(loginToNext) withObject:nilafterDelay:2];//黄色段为方法名,和延迟几秒执行.显示图像:CGRectmyImageRect = CGRectMake(0.0f, 0.0f, 320.0f,109.0f); UIImageView *myImage = [[UIImageViewalloc] initWithFrame:myImageRect];[myImage setImage:[UIImageimageNamed:@"myImage.png"]]; myImage.opaque = YES;//opaque是否透明[self.viewaddSubview:myImage]; [myImagerelease]; WebView:CGRectwebFrame = CGRectMake(0.0, 0.0, 320.0,460.0); UIWebView *webView = [[UIWebView alloc]initWithFrame:webFrame]; [webViewsetBackgroundColor:[UIColor whiteColor]]; NSString*urlAddress = @"http://www.google.com"; NSURL *url= [NSURL URLWithString:urlAddress];NSURLRequest *requestObj =[NSURLRequest requestWithURL:url]; [webViewloadRequest:requestObj];[selfaddSubview:webView]; [webViewrelease];显示网络活动状态指示符这是在iPhone左上部的状态栏显示的转动的图标指示有背景发生网络的活动。UIApplication*app = [UIApplicationsharedApplication]; app.networkActivityIndicatorVisible= YES; 动画:一个接一个地显示一系列的图象NSArray *myImages = [NSArrayarrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImageimageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"],[UIImage imageNamed:@"myImage4.gif"], nil];UIImageView*myAnimatedView = [UIImageViewalloc]; [myAnimatedView initWithFrame:[selfbounds]]; myAnimatedView.animationImages =myImages;//animationImages属性返回一个存放动画图片的数组myAnimatedView.animationDuration =0.25; //浏览整个图片一次所用的时间myAnimatedView.animationRepeatCount = 0; // 0= loops forever 动画重复次数[myAnimatedViewstartAnimating]; [selfaddSubview:myAnimatedView]; [myAnimatedViewrelease]; 动画:显示了something在屏幕上移动。注:这种类型的动画是“开始后不处理”-你不能获取任何有关物体在动画中的信息(如当前的位置)。如果您需要此信息,您会手动使用定时器去调整动画的X和Y坐标这个需要导入QuartzCore.frameworkCABasicAnimation*theAnimation; theAnimation=[CABasicAnimationanimationWithKeyPath:@"transform.translation.x"]; //Createsand returns an CAPropertyAnimation instance for the specified keypath.//parameter:the key path of the property to beanimatedtheAnimation.duration=1; theAnimation.repeatCount=2; theAnimation.autoreverses=YES; theAnimation.fromValue=[NSNumbernumberWithFloat:0]; theAnimation.toValue=[NSNumbernumberWithFloat:-60]; [view.layeraddAnimation:theAnimation forKey:@"animateLayer"];Draggable items//拖动项目Here's how to create a simpledraggable image.//这是如何生成一个简单的拖动图象1. Create a new class thatinherits from UIImageView @interfacemyDraggableImage : UIImageView { } 2. In theimplementation for this new class, add the 2methods: - (void) touchesBegan:(NSSet*)toucheswithEvent:(UIEvent*)event //Retrieve the touch point 检索接触点CGPoint pt = [[touches anyObject]locationInView:self]; startLocation =pt; [[self superview]bringSubviewToFront:self]; }- (void)touchesMoved:(NSSet*)toucheswithEvent:(UIEvent*)event{ // Move relative to theoriginal touch point 相对以前的触摸点进行移动CGPoint pt = [[touches anyObject]locationInView:self]; CGRect frame = [selfframe]; frame.origin.x += pt.x -startLocation.x; frame.origin.y += pt.y -startLocation.y; [selfsetFrame:frame]; 3. Nowinstantiate the new class as you would any other new image and addit to your view //实例这个新的类,放到你需要新的图片放到你的视图上dragger= [[myDraggableImage alloc]initWithFrame:myDragRect]; [draggersetImage:[UIImageimageNamed:@"myImage.png"]]; [draggersetUserInteractionEnabled:YES];线程:1. Createthe new thread: [NSThreaddetachNewThreadSelector:@selector(myMethod) toTarget:selfwithObject:nil]; 2. Create the method that iscalled by the new thread: -(void)myMethod{NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; *** code that should be run in the newthread goes here ***[poolrelease]; //What if you need todo something to the main thread from inside your new thread (forexample, show a loading //symbol)? UseperformSelectorOnMainThread.[selfperformSelectorOnMainThread:@selector(myMethod) withObject:nilwaitUntilDone:false];Plist filesApplication-specific plist filescan be stored in the Resources folder of the app bundle. When theapp first launches, it should check if there is an existing plistin the user's Documents folder, and if not it should copy the plistfrom the app bundle. // Look in Documents for anexisting plist fileNSArray *paths =NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES); NSString*documentsDirectory = [pathsobjectAtIndex:0]; myPlistPath =[documentsDirectorystringByAppendingPathComponent: [NSStringstringWithFormat: @"%@.plist", plistName]]; [myPlistPath retain]; // Ifit's not there, copy it from thebundle NSFileManager *fileManger = [NSFileManagerdefaultManager]; if ( ![fileMangerfileExistsAtPath:myPlistPath]) NSString*pathToSettingsInBundle = [[NSBundle mainBundle]pathForResource:plistNameofType:@"plist"]; //Now readthe plist file from Documents NSArray *paths =NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,NSUserDomainMask, YES); NSString*documentsDirectoryPath = [pathsobjectAtIndex:0]; NSString *path =[documentsDirectoryPathstringByAppendingPathComponent:@"myApp.plist"]; NSMutableDictionary*plist = [NSDictionary dictionaryWithContentsOfFile: path];//Nowread and set key/values myKey = (int)[[plistvalueForKey:@"myKey"] intValue]; myKey2 =(bool)[[plist valueForKey:@"myKey2"]boolValue]; [plist setValue:myKeyforKey:@"myKey"]; [plist writeToFile:pathatomically:YES];AlertsShow a simple alert with OKbutton. UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"An Alert!" delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil]; [alertshow]; [alert release]; InfobuttonIncrease the touchable area on the Info button, so it'seasier to press. CGRect newInfoButtonRect =CGRectMake(infoButton.frame.origin.x-25,infoButton.frame.origin.y-25, infoButton.frame.size.width+50,infoButton.frame.size.height+50); [infoButtonsetFrame:newInfoButtonRect]; Detecting SubviewsYoucan loop through subviews of an existing view. This worksespecially well if you use the "tag" property on your views.for(UIImageView *anImage in [self.view subviews]){if (anImage.tag ==1)         {// do something } }

 

 

16.

//UILabel 和字体大小的匹配,可以用到制作电子书的时候。


   //UILabel 和字体大小的匹配,可以用到制作电子书的时候。

   NSString *str = @"UILabel和字体大小的匹配.亲爱的,在一起的日子很平淡,似乎波澜不惊,只是,这种平凡的日子是最浪漫的,对吗?遇到你之前,世界像一片荒草原;遇到你之后,世界像一个游乐园。过去的许多岁月,对我来说像一缕轻烟,未来的无限生涯,因你而幸福无边。爱一个人是在夜里等待另一个人的呼吸,虽然隔着千里万里,但我知道你在手机的那一端,于是我便会夜夜等待.守株待兔是人间最大的幸福,因为我有目标,你就是我要逮那只兔子,是我一生要好好照顾保护那个人.没有你的时候,你就是我的世界;和你在一起时,世界就是你的。亲爱的,情人节快乐。";

    UIFont *font =[UIFont fontWithName:@"Arial"size:36.0f];

    CGSize size =CGSizeMake(320, 2000);

   

    UILabel *label= [[UILabel alloc] initWithFrame:CGRectZero];//先设为“0”的大小状态

   label.numberOfLines = 0;//当设为0的时候,label显示多行。

   

    CGSizelabelSize = [str sizeWithFont:font constrainedToSize:sizelineBreakMode:UILineBreakModeWordWrap];//得到size的宽和高

   NSLog(@"%f",labelSize.height);

    label.frame =CGRectMake(0, 0,labelSize.width, labelSize.height);

    label.text =str;

    label.font =font;

    label.textColor= [UIColor blueColor];

    [self.viewaddSubview:label];

   

    [labelrelease];



17.选中某一行的时候,该行颜色变化

[tableView deselectRowAtIndexPath:indexPathanimated:NO];//选择当前行,使得改行颜色变化,选中后的反显颜色即刻消失。

 

18.ios 音频后台播放

在按Home的情况下,后台如何播放音乐?

在Info.plist增加一项 Required backgrooundmodes默然是数组,在其下增加一个元素App plays audio

之后在代码中添加:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];

[[AVAudioSession sharedInstance] setActive:YES error:nil];

或者是下面的代码:

       AVAudioSession *session =[AVAudioSession sharedInstance];  

       [session setActive:YESerror:nil];  

       [sessionsetCategory:AVAudioSessionCategoryPlayback error:nil];11:47:36

放到初始化的中或在播放音乐前的即可。

 

19。数组排序


for (int j=0;j<[arrcount];j++)

    {

       for(int i=0; i<[arrcount]-1-j; i++) {

          if ([[arrobjectAtIndex:i] intValue]>[[arr objectAtIndex:i+1] intValue]) {

              aa = [arrobjectAtIndex:i+1];

              [arrreplaceObjectAtIndex:i+1 withObject:[arrobjectAtIndex:i]];

              [arrreplaceObjectAtIndex:i withObject:aa];

             

          }

       }

    }



或者这样。。。。。。。。


//对数组进行排序

-(void)paixuForArray:(NSMutableArray *)_array

{

    NSString*aa;

    for (intj=0;j<[_array count];j++)

    {

       for (int i=0; i<[_array count]-1-j; i++) {

           if ([[[_array objectAtIndex:i] substringWithRange:NSMakeRange(3,4)] intValue]<[[[_array objectAtIndex:i+1]substringWithRange:NSMakeRange(3, 4)] intValue]) {

               aa = [_array objectAtIndex:i+1];

               [_array replaceObjectAtIndex:i+1 withObject:[_arrayobjectAtIndex:i]];

               [_array replaceObjectAtIndex:i withObject:aa];

               

           }

       }

    }

   

}





 

20。获取当前的日期,时间,星期几


    NSDate *date =[NSDate date];

    NSCalendar*calendar = [NSCalendar currentCalendar];

   NSDateComponents *comps;

   

   // 年月日获得

    comps =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit) 

                    fromDate:date];

    NSInteger year= [comps year];

    NSInteger month= [comps month];

    NSInteger day =[comps day];

   NSLog(@"year: %d month: %d, day: %d", year,month, day);

   

   

   //当前的时分秒获得

    comps =[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)

                    fromDate:date];

    NSInteger hour= [comps hour];

    NSIntegerminute = [comps minute];

    NSIntegersecond = [comps second];

   NSLog(@"hour: %d minute: %d second: %d",hour, minute, second);

   

   // 周几和星期几获得

    comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)

                    fromDate:date];

    NSInteger week= [comps week]; // 今年的第几周

    NSIntegerweekday = [comps weekday]; //星期几(注意,周日是“1”,周一是“2”。。。。)

    NSIntegerweekdayOrdinal = [comps weekdayOrdinal]; //这个月的第几周

   NSLog(@"week: %d weekday: %d weekday ordinal:%d", week, weekday, weekdayOrdinal);



参考相关文章介绍,下面两篇文章介绍的很像细。

http://www.2cto.com/kf/201202/118985.html

http://www.cppblog.com/walkklookk/archive/2011/09/15/155852.aspx




 

21。

iPhone随机数

求随机数的三种方法:
1.    srand((unsigned)time(0));
        inti = rand() %5;      

2.    srandom(time(0));
        inti = random() % 5;

3.    inti = arc4random() % 5 (常用) ;

 

参考:

http://www.cocoachina.com/bbs/read.php?tid=70719&keyword=�����

http://www.cocoachina.com/bbs/read.php?tid-2977-fpage-2-toread--page-1.html

http://www.codeios.com/thread-310-1-1.html

 

 

ios编程:iPhone How-to:给导航栏贴图

时间:2011-04-22 csdn博客林家男孩

 

通过tintColor属性可以定制UINavigationBar的背景颜色,但如果需要设定渐变色、甚至纹理来说,就需要贴图了。比较“暴力”的一种做法就是通过Category来重新实现- (void)drawRect:(CGRect)rect的实现,“暴力”是因为这种杀伤面很广,所有项目内的UINavigationBar都会因此改变。这点在应用中应该格外小心。

@interface UINavigationBar(ImageBackground) 

@end 

@implementation UINavigationBar(ImageBackground) 

- (void) drawRect:(CGRect)rect{ 

    [[UIImageimageNamed:@"bkimage.png"] drawInRect:rect]; 

@end

0 0
原创粉丝点击