OC&&IOS开发小技巧总结
1.数组遍历的三种方式
2. 使用 [obj class]属性获得类名成,利用类名称创建对象
3.给一个UIImageView 添加一个动画数组,可以设置动画时间,循环次数
4.利用[UIImage animatedImageNamed:@“” duration:]可以达到蝴蝶翩翩飞过,的效果,不过要开一个定时器,才能让图片横向的移动
5. 给Button设置背景图片,并且button的大小跟图片的大小一样大
6.用addViewController做类似于导航控制器的作用
7.打电话
8.给导航栏添加图片
9.生成二维码图片(包含链接),并且添加视图上
10.给一个View设置层的边框颜色,边框宽度,变的圆角,
11.给一个Lable添加NSAttributeString,包含设置字体,字的间距,字体的颜色,字体的大小
12获得改字符串的大小
13.一个视图控制器退出的时候,要隐藏系统的底部的导航栏
14.创建前后颜色不同的字符串
15.给UITableView去掉分割线
16.给某个View的下方添加波浪线
17.获得IP地址及Mac地址
18.创建一个UIImageView,并且设置渐变色
19.设置UITableView的某个cell不可选
21.隐藏和现实导航栏,只管本视图控制器的navagationController的显示和隐藏,不影响其他的视图控制器
22.原生的给设置tabBarItem设置图片,字体,以及设置,文字和图片之间距离
23.给字符串添加下划线
24.给导航栏的标题设置文字的颜色,字体的大小
25,断网的判断及处理,要包含Reachability.h的头文件
25,断网的判断及处理,要包含Reachability.h的头文件
26.动态将UITableViewCell滚动到指定的cell
27.一段文字设置行间距
28.签到动画
29.给城市排序按照拼音
30.发邮件,打电话,发短信,打开网址
32.判断手机网络运营商
33 NSData同步请求网络数据
34view和window之间坐标转换
35.ViewController的生命周期
36程序启动原理
37.UITableViewCell 文字位置调整
38.ios带圆角图片的拉伸
39自定义UINavigtion
1.数组遍历的三种方式(for ,for in ,枚举器)
int main(int argc, const char * argv[]) { @autoreleasepool { //创建一个Car类,两个属性:名字,颜色 //创建3个对象,加到数组里 //输出数组 Car *car1 = [[Car alloc] initWithName:@"宝马汽车" andColor:'R']; Car *car2 = [[Car alloc] initWithName:@"奔驰汽车" andColor:'B']; Car *car3 = [[Car alloc] initWithName:@"奥迪汽车" andColor:'W']; NSArray *array = [NSArray arrayWithObjects:car1,car2,car3, nil]; //循环遍历数组 [[array objectAtIndex:0] setName:@"拖拉机"]; // for(int i = 0; i < [array count]; i++) // { // NSLog(@"%@",[array objectAtIndex:i]); // } //for in //快速遍历数组 //从前往后 完整遍历 //数组中有多种对象的时候用id //可变数组的时候,并且要改变数组长度的时候不要用 for(Car *obj in array) { NSLog(@"%@",obj); } //枚举器用来遍历数组 //- (NSEnumerator *)objectEnumerator; //1 2 3 4 5 6 //把数组的所有元素依次存放到枚举器 NSEnumerator *enumerator = [array objectEnumerator]; enumerator = [array reverseObjectEnumerator]; id obj = nil; while(obj = [enumerator nextObject]){ NSLog(@"%@",obj); } while(obj = [enumerator nextObject]) { NSLog(@"%@",obj); } 枚举器block [moduleArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { }]; } return 0; }
2. 使用 [obj class]属性获得类名成,利用类名称创建对象
#import #import "mybuton.h" int main(int argc, const char * argv[]) { @autoreleasepool { mybuton*btn=[mybuton creatBtn:SJX]; [btn showType]; } return 0; } #import typedef enum { SJX, YX }BtnType; @interface mybuton : NSObject -(void)showType; +(instancetype)creatBtn:(BtnType)type; @end #import "mybuton.h" #import"mybuton_SJX.h" #import "mybuton_YX.h" @implementation mybuton -(void)showType { NSLog(@"我是一个按钮"); } +(instancetype)creatBtn:(BtnType)type { Class myclass[]={[mybuton_SJX class],[mybuton_YX class]}; mybuton*btn=[[myclass[type]alloc]init]; return btn; } @end #import "mybuton.h" @interface mybuton_SJX : mybuton @end #import "mybuton_SJX.h" @implementation mybuton_SJX -(void)showType{ NSLog(@"我是一个三角形按钮"); } @end
3.给一个UIImageView 添加一个动画数组,可以设置动画时间,循环次数
images = [NSArray arrayWithObjects: [UIImage imageNamed:@"1.jpg"], [UIImage imageNamed:@"2.jpg"], [UIImage imageNamed:@"3.jpg"], [UIImage imageNamed:@"4.jpg"], [UIImage imageNamed:@"5.jpg"], nil]; // 设置iv控件需要动画显示的图片为images集合元素 self.iv.animationImages = images; // 设置动画持续时间 self.iv.animationDuration = 12; // 设置动画重复次数 self.iv.animationRepeatCount = 999999; // 让iv控件开始播放动画 [self.iv startAnimating]; 可以每隔2.4s动画,更新图片,循环99999次
4.利用[UIImage animatedImageNamed:@“” duration:]可以达到蝴蝶翩翩飞过,的效果,不过要开一个定时器,才能让图片横向的移动
// 定义显示图片的UIImageView控件 UIImageView* iv; // 定义定时器 NSTimer* timer; - (void)viewDidLoad { [super viewDidLoad]; // 设置背景色为白色 self.view.backgroundColor = [UIColor whiteColor]; // 创建UIImageView控件 iv = [[UIImageView alloc] initWithFrame:CGRectMake(0 , 30 , 41 , 43)]; // 使用UIImageView加载文件名以butterfly_f开头的多张图片 iv.image = [UIImage animatedImageNamed:@"butterfly_f" duration:0.6]; // 将UIImageView添加到系统界面上 [self.view addSubview: iv]; // 启动NSTimer定时器来改变UIImageView的位置 timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changePos) userInfo:nil repeats:YES]; } - (void) changePos { CGPoint curPos = iv.center; // 计算一个-4~5之间随机数 int y = arc4random() % 10 - 4; // 当curPos的x坐标已经超过了屏幕的宽度 if(curPos.x > [UIScreen mainScreen].bounds.size.width) { // 控制蝴蝶再次从屏幕左侧开始移动 iv.center = CGPointMake(0, 30); } else { // 通过修改iv的center属性来改变iv控件的位置 iv.center = CGPointMake(curPos.x + 4, curPos.y + y); } }
5. 给Button设置背景图片,并且button的大小跟图片的大小一样大
UIImage* backImg = [UIImage imageNamed:@"back_white"]; UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, backImg.size.width, backImg.size.height)]; [btn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside]; [btn setImage:backImg forState:UIControlStateNormal]; //[btn setImage:backImg forState:UIControlStateHighlighted]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
6.用addViewController做类似于导航控制器的作用
ResultViewController *result = [[ResultViewController alloc] initWithNibName:@"ResultViewController" bundle:nil]; [self.parentViewController addChildViewController:result]; [self.parentViewController.view addSubview:result.view]; result.view.frame = CGRectMake(WIDTH, 0, WIDTH, HEIGHT); [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ CATransition *animation = [CATransition animation]; [animation setDuration:0.3]; [animation setType:kCATransitionPush]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]]; [animation setSubtype:kCATransitionFromRight]; [self.navigationController.view.layer addAnimation:animation forKey:nil]; result.view.frame = CGRectMake(0, 0, WIDTH, HEIGHT); } completion:^(BOOL finished) { }];
7.打电话
如果是飞行模式,手机系统会弹出是否停用飞行模式
如果没有卡,也会提示
如果有卡,并且不是飞行模式,程序会自动进入后台,前台会弹出拨号的界面
#pragma mark - 打电话 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{ NSLog(@"打电话"); if (buttonIndex==0) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",@"4008-230-950"]]]; } }
8.给导航栏添加图片
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth*0.3, 22)]; imageView.image=[UIImage imageNamed:@"tapmoney"]; self.navigationItem.titleView=imageView;
9.生成二维码图片(包含链接),并且添加视图上
前提是要导入ZBar.h和QRCodeGenerator.h头文件
UIImageView *twoDimensionCode=[WNController createImageViewWithFrame:CGRectMake(ViewWidth*0.2, ViewHeight*0.02, ViewWidth*0.5, ViewHeight*0.20) ImageName:nil]; twoDimensionCode.image=[QRCodeGenerator qrImageForString:@"www.baidu.com" imageSize:400]; [view addSubview:twoDimensionCode];
10.给一个View设置层的边框颜色,边框宽度,变的圆角,
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(ViewWidth*0.05, 10, ViewWidth*0.9, ViewHeight*0.4)]; view.layer.borderColor=[[UIColor blackColor]CGColor]; view.layer.borderWidth=0.5; view.layer.cornerRadius=5; view.layer.masksToBounds=YES; [self.view addSubview:view];
11.给一个Lable添加NSAttributeString,包含设置字体,字的间距,字体的颜色,字体的大小
NSAttributedString *attriStrTodayEarn =[[NSAttributedString alloc] initWithString:@"Today's earn" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor],NSKernAttributeName : @(-1.3f),NSFontAttributeName:[UIFont fontWithName:@"Gill Sans" size:1.8*NormalFont]}]; [todayEarn setAttributedText:attriStrTodayEarn];
12获得改字符串的大小
CGSize size=[middleLabel.text boundingRectWithSize:CGSizeMake(ViewWidth*0.7,NormalFont*3) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:middleLabel.font} context:nil].size;
13.一个视图控制器退出的时候,要隐藏系统的底部的导航栏
vc.hidesBottomBarWhenPushed=YES;
14.创建前后颜色不同的字符串
- (NSMutableAttributedString *)createAttributeStringWithStr:(NSString *)foreString withStr:(NSString *)afterString { NSString * joinstr = foreString; NSString * text = afterString; NSString *jointext = [NSString stringWithFormat:@"%@%@",joinstr,text]; NSDictionary *textDic = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.13f green:0.65f blue:0.00f alpha:1.00f],NSFontAttributeName:[UIFont systemFontOfSize:NormalFont ]}; NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:jointext]; [attributeString addAttributes:textDic range:NSMakeRange(joinstr.length, text.length)]; return attributeString; //本质是NSMutableAttributedString 给一定范围的字符做颜色属性的改变 }
15.给UITableView去掉分割线
_tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
16.给某个View的下方添加波浪线
-(void)drawRect:(CGRect)rect{ CGRect frame=self.frame; CGFloat height=frame.size.height; // CGFloat width =frame.size.width; UIColor *color = [UIColor whiteColor]; [color set]; //设置线条颜 UIBezierPath* aPath = [UIBezierPath bezierPath]; aPath.lineWidth = 0.5; aPath.lineCapStyle = kCGLineCapRound; //线条拐角 aPath.lineJoinStyle = kCGLineCapRound; //终点处理 aPath.lineCapStyle = kCGLineCapRound; //线条拐角 aPath.lineJoinStyle = kCGLineCapRound; //终点处理 for (int i=0; i<50; ++i) { [aPath moveToPoint:CGPointMake(0+frame.size.width/50*i, height)]; [aPath addQuadCurveToPoint:CGPointMake(frame.size.width/50*(i+1), height) controlPoint:CGPointMake(frame.size.width/100+frame.size.width/50*i, height-5)]; [aPath fill]; }
17.获得IP地址及Mac地址
前提要包含
#import #import #include #include #include #include +(NSString *)getMACAddress{ int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex("en0")) == 0) { printf("Error: if_nametoindex error/n"); return NULL; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1/n"); return NULL; } if ((buf = malloc(len)) == NULL) { printf("Could not allocate memory. error!/n"); return NULL; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return NULL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; free(buf); return [outstring uppercaseString]; } +(NSString *)getIPAddress{ NSString *address = @"error"; struct ifaddrs *interfaces = NULL; struct ifaddrs *temp_addr = NULL; int success = 0; // retrieve the current interfaces - returns 0 on success success = getifaddrs(&interfaces); if (success == 0) { //Loop through linked list of interfaces temp_addr = interfaces; while(temp_addr != NULL) { if(temp_addr->ifa_addr->sa_family == AF_INET) { // Check if interface is en0 which is the wifi connection on the iPhone if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { // Get NSString from C String address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } // Free memory freeifaddrs(interfaces); return address; }
18.创建一个UIImageView,并且设置渐变色
+(UIImageView *)progressiveImageframe:(CGRect)frame beginColor:(CGFloat *)Bcomponent endColor:(CGFloat*)Ecomponent { UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame]; UIGraphicsBeginImageContext(imageView.frame.size); [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)]; CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); //设置线条终点形状 CGContextRef context =UIGraphicsGetCurrentContext(); CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); // 创建起点颜色 (CGFloat[]){0, 0.61, 0.81, 1} (CGFloat[]){0.87, 0.61, 0, 1} CGColorRef beginColor = CGColorCreate(colorSpaceRef,Bcomponent ); // 创建终点颜色 CGColorRef endColor = CGColorCreate(colorSpaceRef, Ecomponent); // 创建颜色数组 CFArrayRef colorArray = CFArrayCreate(kCFAllocatorDefault, (const void*[]){beginColor, endColor}, 2, nil); // 创建渐变对象 CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpaceRef, colorArray, (CGFloat[]){ 0.0f, // 对应起点颜色位置 1.0f // 对应终点颜色位置 }); // 释放颜色数组 CFRelease(colorArray); // 释放起点和终点颜色 CGColorRelease(beginColor); CGColorRelease(endColor); // 释放色彩空间 CGColorSpaceRelease(colorSpaceRef); CGContextDrawLinearGradient(context, gradientRef, CGPointMake(0, 0), CGPointMake(0, frame.size.height), 0); CGGradientRelease(gradientRef); imageView.image=UIGraphicsGetImageFromCurrentImageContext(); return imageView; }
19.设置UITableView的某个cell不可选
为了彻底避免UITableViewCell选择,让UITableViewDelegate实现tableView:willSelectRowAtIndexPath:。如果你不希望选中行,从那个函数可以返回nil
- (NSIndexPath *)tableView:(UITableView *)tv willSelectRowAtIndexPath:(NSIndexPath *)path { //根据 NSIndexPath判定行是否可选。 if (rowIsSelectable) { returnpath; } returnnil; }
20.自定义一个CustomView给一个UIImageView添加一个点击的block
#import @interface CustomImageView : UIImageView @property(nonatomic,copy)void(^touchImage)(); @end #import "CustomImageView.h" @implementation CustomImageView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.userInteractionEnabled=YES; } return self; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ if (self.touchImage) { self.touchImage(); } } @end
21.隐藏和现实导航栏,只管本视图控制器的navagationController的显示和隐藏,不影响其他的视图控制器
-(void)viewWillAppear:(BOOL)animated{ [super viewDidAppear:YES]; self.navigationController.navigationBarHidden=YES; } -(void)viewWillDisappear:(BOOL)animated{ self.navigationController.navigationBarHidden=NO; }
22.原生的给设置tabBarItem设置图片,字体,以及设置,文字和图片之间距离
nc.tabBarItem = [[UITabBarItem alloc]initWithTitle:titles[i] image:[[UIImage imageNamed:imageArr[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:selectedImageArr[i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]]; [nc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -4)]; [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor], NSForegroundColorAttributeName,[UIFont systemFontOfSize:SmallFont*0.9] ,NSFontAttributeName,nil] forState:UIControlStateNormal]; [[UITabBarItem appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIColor orangeColor],NSForegroundColorAttributeName, nil]forState:UIControlStateSelected];
23.给字符串添加下划线
UILabel * standardF = [self createSingleLabelWithFrame:CGRectMake(space*4, CGRectGetMaxY(standard.frame)+space, ViewWidth-space*4, space*3) withAttributedString:@"亚马逊礼品卡使用协议"]; [self.view addSubview:standardF]; UILabel * standardW = [self createSingleLabelWithFrame:CGRectMake(space*4, CGRectGetMaxY(standardF.frame), ViewWidth-space*4, space*3) withAttributedString: @"个人资料隐私及保护协议"]; [self.view addSubview:standardW]; } - (UILabel *)createSingleLabelWithFrame:(CGRect)frame withAttributedString:(NSString *)text { NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:text]; [attributedStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, attributedStr.length)]; UILabel *label = [WNController createLabelWithFrame:frame Font:NormalFont Text:nil]; label.attributedText = attributedStr; label.textColor = [UIColor orangeColor]; return label; }
24.给导航栏的标题设置文字的颜色,字体的大小
self.title = @"检查新版本"; //标题栏 [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"topback.png"] forBarMetrics:UIBarMetricsDefault]; NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:KDefaultTitleViewTitleColor, NSForegroundColorAttributeName, KDefaultTitleViewTitleFont, NSFontAttributeName, nil]; [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes]
25,断网的判断及处理,要包含Reachability.h的头文件
Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; NetworkStatus status = [reach currentReachabilityStatus]; if (status == NotReachable) { //没有连接到网络就弹出提实况 [[[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败,请稍后再试!" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil] show]; return; }
26.动态将UITableViewCell滚动到指定的cell
[_tableViewscrollToRowAtIndexPath:[NSIndexPathindexPathForRow:_messageArray.count-1inSection:0]atScrollPosition:UITableViewScrollPositionNoneanimated:YES];
27.一段文字设置行间距
commentLabel.textColor=UIColorFromRGB(0x333333,1.0);
//设置行间距
NSMutableAttributedString*attributedString = [[NSMutableAttributedStringalloc]initWithString:commentLabel.text];
NSMutableParagraphStyle*paragraphStyle = [[NSMutableParagraphStylealloc]init];
[paragraphStylesetLineSpacing:lineSpace];
[attributedStringaddAttribute:NSParagraphStyleAttributeNamevalue:paragraphStylerange:NSMakeRange(0, [attributedStringlength])];
//设置昵称颜色为橘黄色
28.签到动画
-(void)reallyStartAnimation { if ( !self.isCheckingIn ) { self.checkImageView.image = [UIImage imageNamed:@"checkin-2"]; [self.checkBtn setTitle:@"签到中.." forState:UIControlStateNormal]; [self startAnimation]; self.isCheckingIn = YES; } } -(void) startAnimation { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.01]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(endAnimation)]; self.checkImageView.transform = CGAffineTransformMakeRotation(self.angle * (M_PI / 180.0f)); [UIView commitAnimations]; } -(void)endAnimation { self.angle += 10; [self startAnimation]; }
29.给城市排序安装拼音
-(void)buildUpFirstLetterDictionary { self.citySortedCommunityDic = [[NSMutableDictionary alloc] initWithCapacity:16]; self.citySortedHeaderTitleIndexDic = [[NSMutableDictionary alloc] initWithCapacity:16]; for (City* city in self.cityDataSource.citys) { NSMutableArray* originalCommunityArray = [[NSMutableArray alloc] initWithCapacity:16]; for ( Community* community in city.communitys.communitys ) { [originalCommunityArray addObject:community.name]; } NSDictionary* dic = [originalCommunityArray sortedArrayUsingFirstLetter]; [self.citySortedCommunityDic setObject:dic forKey:city.name]; //因为字典的无序,将所有的key取出来之后,重新输出 NSArray *keys = [[dic allKeys] sortedArrayUsingSelector:@selector(compare:)]; [self.citySortedHeaderTitleIndexDic setObject:keys forKey:city.name]; } } ///// #import "NSArray+FirstLetterArray.h" #import "pinyin.h" @implementation NSArray (FirstLetterArray) - (NSDictionary *)sortedArrayUsingFirstLetter { NSMutableDictionary *mutDic = [NSMutableDictionary dictionary]; const char *letterPoint = NULL; NSString *firstLetter = nil; for (NSString *str in self) { //检查 str 是不是 NSString 类型 if (![str isKindOfClass:[NSString class]]) { assert(@"object in array is not NSString"); #ifdef DEBUG NSLog(@"object in array is not NSString, it's [%@]", NSStringFromClass([str class])); #endif continue; } letterPoint = [str UTF8String]; //如果开头不是大小写字母则读取 首字符 if (!(*letterPoint > 'a' && *letterPoint < 'z') && !(*letterPoint > 'A' && *letterPoint < 'Z')) { //汉字或其它字符 char letter = pinyinFirstLetter([str characterAtIndex:0]); letterPoint = &letter; } //首字母转成大写 firstLetter = [[NSString stringWithFormat:@"%c", *letterPoint] uppercaseString]; //首字母所对应的 姓名列表 NSMutableArray *mutArray = [mutDic objectForKey:firstLetter]; if (mutArray == nil) { mutArray = [NSMutableArray array]; [mutDic setObject:mutArray forKey:firstLetter]; } [mutArray addObject:str]; } //字典是无序的,数组是有序的, //将数组排序 for (NSString *key in [mutDic allKeys]) { NSArray *nameArray = [[mutDic objectForKey:key] sortedArrayUsingSelector:@selector(compare:)]; [mutDic setValue:nameArray forKey:key]; } return mutDic; } @end
30.发邮件,打电话,发短信,打开网址
30.1、调用 自带mail [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@hzlzh.com”]]; 30.2、调用 电话phone [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://8008808888"]]; iOS应用内拨打电话结束后返回应用 一般在应用中拨打电话的方式是: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://123456789"]]; 使用这种方式拨打电话时,当用户结束通话后,iphone界面会停留在电话界面。 用如下方式,可以使得用户结束通话后自动返回到应用: UIWebView*callWebview =[[UIWebView alloc] init]; NSURL *telURL =[NSURL URLWithString:@"tel:10086"];// 貌似tel:// 或者 tel: 都行 [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]]; //记得添加到view上 [self.view addSubview:callWebview]; 还有一种私有方法:(可能不能通过审核) [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"]]; 30.3、调用 SMS [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]]; 30.4、调用自带 浏览器 safari [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.hzlzh.com"]]; 调用phone可以传递号码,调用SMS 只能设定号码,不能初始化SMS内容。 若需要传递内容可以做如下操作: 加入:MessageUI.framework #import 实现代理:MFMessageComposeViewControllerDelegate 调用sendSMS函数 //内容,收件人列表 - (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients { MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease]; if([MFMessageComposeViewController canSendText]) { controller.body = bodyOfMessage; controller.recipients = recipients; controller.messageComposeDelegate = self; [self presentModalViewController:controller animated:YES]; } } // 处理发送完的响应结果 - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result { [self dismissModalViewControllerAnimated:YES]; if (result == MessageComposeResultCancelled) NSLog(@"Message cancelled") else if (result == MessageComposeResultSent) NSLog(@"Message sent") else NSLog(@"Message failed") } 默认发送短信的界面为英文的,解决办法为: 在.xib 中的Localization添加一組chinese就ok了
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"]; NSLog(@"第一次启动"); }else{ NSLog(@"不是第一次启动"); }32.判断手机运营商
- (BOOL)checkChinaMobile { BOOL ret = NO; CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init]; CTCarrier *carrier = [info subscriberCellularProvider]; if (carrier == nil) { [info release]; return NO; } NSString *code = [carrier mobileNetworkCode]; if (code == nil) { [info release]; return NO; } if ([code isEqualToString:@"00"] || [code isEqualToString:@"02"] || [code isEqualToString:@"07"]) { ret = YES; } [info release]; return ret; }
其它网络判断参考下表:
MCC | MNC | Brand | Operator | Status | Bands (MHz) | References and notes |
---|---|---|---|---|---|---|
460 | 00 | China Mobile | China Mobile | Operational | GSM 900 / GSM 1800 / TD-SCDMA 1880 / TD-SCDMA 2010 | |
460 | 01 | China Unicom | China Unicom | Operational | GSM 900 / GSM 1800 / UMTS 2100 | CDMA network sold to |
460 | 02 | China Mobile | China Mobile | Operational | GSM 900 / GSM 1800 / TD-SCDMA 1880 / TD-SCDMA 2010 | |
460 | 03 | China Telecom | China Telecom | Operational | CDMA2000 800 / CDMA2000 2100 | EV-DO |
460 | 05 | China Telecom | China Telecom | Operational | ||
460 | 06 | China Unicom | China Unicom | Operational | GSM 900 / GSM 1800 / UMTS 2100 | |
460 | 07 | China Mobile | China Mobile | Operational | GSM 900 / GSM 1800 / TD-SCDMA 1880 / TD-SCDMA 010 | |
460 | 20 | China Tietong | China Tietong | Operational | GSM-R |
33 NSData同步请求网络数据
+ (id)dataWithContentsOfURL:(NSURL *)url; + (id)dataWithContentsOfURL:(NSURL *)url options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; 其中NSDataReadingOptions可以附加一个参数。NSDataReadingMappedIfSaf e参数。使用这个参数后,iOS就不会把整个文件全部读取的内存了,而是将文件映射到进程的地址空间中,这么做并不会占用实际内存。这样就可以解决内存满的问题。 补充: url包含中文时,直接使用会出错,需要如下转换 NSURL *url = [NSURL URLWithString:[self.curTaskData.urlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
34view和window之间坐标转换
在某UIView子函数内部,将centerPoint从子view坐标转换成appDelegate.window内的坐标:
CGPointcenterPoint = [selfgetCenterPointByCurPressPoint:pressPointer];
centerPoint = [selfconvertPoint:centerPointtoView:appDelegate.window];
35.ViewController的生命周期
loadView和viewDidLoad的区别就是,loadView时view还没有生成,viewDidLoad时,view已经生成了,loadView只会被调用一次,而viewDidLoad可能会被调用多次(View可能会被多次加载),当view被添加到其他view中之前,会调用viewWillAppear,之后会调用viewDidAppear。当view从其他view中移除之前,调用viewWillDisAppear,移除之后会调用viewDidDisappear。当view不再使用时,受到内存警告时,ViewController会将view释放并将其指向为nil。
ViewController的生命周期中各方法执行流程如下:
init—>loadView—>viewDidLoad—>viewWillApper—>viewDidApper—>viewWillDisapper—>viewDidDisapper—>viewWillUnload->viewDidUnload—>dealloc
36程序启动原理
UIApplication和delegate
所有的移动操作系统都有个致命的缺点:app很容易受到打扰.比如一个来电或者锁屏会导致app进入后台甚至被终止;
还有很多其他类似的情况会导致app受到干扰,在app受到干扰时,会产生一些系统事件,这时UIApplication会通知它的delegate对象,让delegate来处理这些系统事件.
delegate可处理的事件包括:
1> 应用程序的生命周期事件(如程序的启动和关闭);
2> 系统事件(如来电);
3> 内存警告...
UIWindow的获得:
1 | [UIApplicationsharedApplication].windows |
在本应用中打开的UIWindow列表,这样就可以接触应用中的任何一个UIView对象(平时输入文字弹出的键盘,就处在一个新的UIWindow中).
1 | [UIApplicationsharedApplication].keyWindow |
用来接收键盘以及非触摸类的消息事件的UIWindow,而且程序中每时每刻只能有一个UIWindow是keyWindow.如果某个UIWindow内部的文本框不能输入文字,可能是因为这个UIWindow不是keyWindow.
1 | view.window |
获得某个UIView所在的UIWindow.
37.UITableViewCell 文字位置调整
继承UITableViewCell,然后实现layoutSubviews函数,如下代码把textlabel下移了10个像素:
- (void) layoutSubviews
{
[superlayoutSubviews];
intcellHeight =self.frame.size.height;
intcellWidth =self.frame.size.width;
self.textLabel.frame=CGRectMake(0,10,cellWidth, cellHeight-10);
}
38.ios带圆角图片的拉伸
UIImage* aImage =[[UIImageimageNamed:@"xxx.png"]stretchableImageWithLeftCapWidth:3topCapHeight:3];
原图边框内的3个像素不拉伸,中间部分按需要拉伸,可以保持圆角不被破坏
39自定义UINavigtion
1如果只是要更改left button 或者right button 的背景颜色: UINavigationBar* aNavigationBar = self.navigationController.navigationBar; aNavigationBar.tintColor = [UIColor lightGrayColor]; 2,如果要自定义left button 或者right button 的背景图片: UIButton* backButton = [customNavigationBar backButtonWith:[UIImage imageNamed:@"navigationBarBackButton.png"] highlight:nilleftCapWidth:14.0]; backButton.titleLabel.textColor = [UIColor colorWithRed:254.0/255.0 green:239.0/255.0 blue:218.0/225.0 alpha:0.5]; self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease]; 3,如果要自定义navigation整个的背景图片: 1,自定义navigationbar,然后在这个自定义类中实现如下函数 - (void)drawRect:(CGRect)rect { if (navigationBarBackgroundImage) [navigationBarBackgroundImage drawInRect:rect]; else [super drawRect:rect];,如果只是要更改left button 或者right button 的背景颜色: UINavigationBar* aNavigationBar = self.navigationController.navigationBar; aNavigationBar.tintColor = [UIColor lightGrayColor]; 2,如果要自定义left button 或者right button 的背景图片: UIButton* backButton = [customNavigationBar backButtonWith:[UIImage imageNamed:@"navigationBarBackButton.png"] highlight:nilleftCapWidth:14.0]; backButton.titleLabel.textColor = [UIColor colorWithRed:254.0/255.0 green:239.0/255.0 blue:218.0/225.0 alpha:0.5]; self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease]; 3,如果要自定义navigation整个的背景图片: 1,自定义navigationbar,然后在这个自定义类中实现如下函数 - (void)drawRect:(CGRect)rect { if (navigationBarBackgroundImage) [navigationBarBackgroundImage drawInRect:rect]; else [super drawRect:rect];
下一篇: iOS开发之生命周期解析