iPhone常见用法

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]]]]; } 多线程(这种方式,只管建立线程,不管回收线程,为什么大家都只会这种方式) [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.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; //水平翻转 [self presentModalViewController:settings animated:YES]; [settings release]; 9.NSScrollView 滑动用法: -(void) scrollViewDidScroll:(UIScrollView *)scrollView{ NSLog(@"正在滑动中..."); } //用户直接滑动NSScrollView,可以看到滑动条 -(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView { } // 通过其他控件触发NSScrollView滑动,看不到滑动条 - (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { } 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]; srandom(time(NULL)); //随机数种子 id d = random(); // 随机数 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,ActionSheet的cancelButton点击事件: 代码 -(void) actionSheet UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex { NSLog(@"cancel actionSheet........"); //当用户按下cancel按钮 if( buttonIndex == [actionSheet cancelButtonIndex]) { exit(0); } // //当用户按下destructive按钮 // if( buttonIndex == [actionSheet 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 beginAnimations:nil context:NULL]; [self pushViewController:controller animated:NO]; [UIView setAnimationDuration:.5]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationTransition:transition forView:self.view cache:YES]; [UIView commitAnimations]; } 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]; 20.计算字符串长度: CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width; 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.给图层添加背景图片://这里都是layer的,要研究下layer 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];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值