iOS从入门到颈椎病发作

来源:互联网 发布:淘宝店铺月销售额查询 编辑:程序博客网 时间:2024/04/29 15:34

个人iOS学习笔记~
1.检测网络状态

//监测网络状态    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {        //status即为判断的状态        if (status == AFNetworkReachabilityStatusReachableViaWiFi) {            NSLog(@"Wifi");        }else if (status == AFNetworkReachabilityStatusReachableViaWWAN){            NSLog(@"GPRS/3G");        }else if (status == AFNetworkReachabilityStatusNotReachable){            NSLog(@"网络未连接");        }else if (status == AFNetworkReachabilityStatusUnknown){            NSLog(@"不能识别");        }    }];    //启动网络检测  Monitoring监测    [manager.reachabilityManager startMonitoring];    //原理即为调用Block

2.文件下载(系统原生)

- (void)downloadFile{//    NSString * url = @"http://10.10.158.179/1530/lalala.mp3";    NSString * url = @"http://image2.90e.com/image/1600x900/1497.jpg";    //创建下载器    AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];    //进行擦除中文 转码操作    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//    NSLog(@"%@",url);    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];    //下载任务    /*     1、请求对象     2、进度     */    //进度    __autoreleasing NSProgress * progress = nil;    //当调用下方block时候会自动创建preogress对象,更改其值    NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {        //告诉下载器 将文件下载到哪个路径        //找到程序的文件夹 沙盒路径        NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"3.jpg"];        return [NSURL fileURLWithPath:path];    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {        //下载完成的回调        if (error) {            NSLog(@"%@",error);        }else{            NSLog(@"下载完成");        }    }];    //启动下载    [task resume];    NSLog(@"%@",NSHomeDirectory());    _progress = progress;    [_progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];}- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    if (object == _progress && [keyPath isEqualToString:@"fractionCompleted"]) {        //监测进度        NSLog(@"%.2f",_progress.fractionCompleted);    }}

3.Post请求

 数据请求方式 1、Get  通常用于下载数据 网址以明文的形式进行显示  特点:主网址后需添加?,?后面进行拼接参数,多个参数之间以&进行拼接 2、Post 通常用于上传数据 网址以密文的形式进行显示 不会使网址的参数外漏 多用于登录或注册账号 特点:主网址后无需添加?,所需参数需添加到网址的附加信息中(以字典的形式进行存储) 保密程度高 */
- (void)postRequest{    NSString * url = @"http://10.0.8.8/sns/my/login.php";    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    //POST的附加信息 parameters后即为所需传的参数    NSDictionary * dict = @{@"username":@"sure0705",@"password":@"zq851099"};    [manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];        NSLog(@"%@",dict[@"message"]);    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        NSLog(@"请求失败");    }];}

4.重写KVC防止报错

//重写方法 以防报错- (void)setValue:(id)value forUndefinedKey:(NSString *)key{    NSLog(@"没有找到Key:%@",key);}

5.// button字体竖向显示

 [button.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];

6.指定四个角为圆角

 UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];    view2.backgroundColor = [UIColor redColor];    [self.view addSubview:view2];    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];    maskLayer.frame = view2.bounds;    maskLayer.path = maskPath.CGPath;    view2.layer.mask = maskLayer;只需修改* UIRectCornerTopLeft* UIRectCornerTopRight* UIRectCornerBottomLeft* UIRectCornerBottomRight* UIRectCornerAllCorners

7.断点定位程序崩溃处

add Exception Breakpoint

8.去掉cell的分割线

//去掉分割线    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;

9.去掉cell选中效果

//去掉cell选中效果    cell.selectionStyle = UITableViewCellSelectionStyleNone;

10.xcode7 http请求

1   在Info.plist中添加NSAppTransportSecurity类型Dictionary。    2   在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES

11.时间戳

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];    [formatter setTimeZone:timeZone];    NSDate *datenow = [NSDate date];    //设置一个字符串的时间    NSMutableString *datestring = [listdic objectForKey:@"FIRSTTIME"];//    //注意 如果20141202052740必须是数字,如果是UNIX时间,不需要下面的插入字符串。//    [datestring insertString:@"-" atIndex:4];//    [datestring insertString:@"-" atIndex:7];//    [datestring insertString:@" " atIndex:10];//    [datestring insertString:@":" atIndex:13];//    [datestring insertString:@":" atIndex:16];    NSLog(@"datestring==%@",datestring);    NSDateFormatter * dm = [[NSDateFormatter alloc]init];    //指定输出的格式   这里格式必须是和上面定义字符串的格式相同,否则输出空    [dm setDateFormat:@"YYYY-MM-dd HH:mm:ss"];    NSDate * newdate = [dm dateFromString:datestring];    long dd = (long)[datenow timeIntervalSince1970] - [newdate timeIntervalSince1970];    NSString *timeString=@"";     NSString *timeString2=@"";    NSString *timeString3=@"";    NSString *timeString4=@"";    timeString = [NSString stringWithFormat:@"%ld", dd/3600];//时    timeString2 = [NSString stringWithFormat:@"%ld", (dd%3600)/60];//分    timeString3=[NSString stringWithFormat:@"%@小时%@分钟", timeString,timeString2];    timeString4 = [NSString stringWithFormat:@"%ld", dd/86400];//天    if (dd/86400>1)            {                timeString = [NSString stringWithFormat:@"%ld", (dd%86400)/3600];//时                timeString4 = [NSString stringWithFormat:@"%ld", dd/86400];//天                timeString2 = [NSString stringWithFormat:@"%ld", ((dd%86400)%3600)/60];//分               timeString3=[NSString stringWithFormat:@"%@天%@小时", timeString4,timeString];            }    if (dd/3600<1)            {                timeString = [NSString stringWithFormat:@"%ld", dd/60];                timeString3=[NSString stringWithFormat:@"%@分钟", timeString];            }   if (dd/3600>1&&dd/86400<1){        timeString3=[NSString stringWithFormat:@"%@小时%@分钟", timeString,timeString2];    }

12 ios 数组最大值,最小值,平均值,和的快速算法

NSArray *testArray = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0",@"10",nil];    NSNumber *sum1 = [testArray valueForKeyPath:@"@sum.floatValue"];    NSNumber *avg1 = [testArray valueForKeyPath:@"@avg.floatValue"];    NSNumber* max1=[testArray valueForKeyPath:@"@max.floatValue"];    NSNumber* min1=[testArray valueForKeyPath:@"@min.floatValue"];    NSLog(@"%@ %@ %@ %@",sum1,avg1,max1,min1);

13 iOS-获取当前时间的年、月、日、时、分、秒

//获取当前时间NSDate *now = [NSDate date];NSLog(@"now date is: %@", now);NSCalendar *calendar = [NSCalendar currentCalendar];NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];int year = [dateComponent year];int month = [dateComponent month];int day = [dateComponent day];int hour = [dateComponent hour];int minute = [dateComponent minute];int second = [dateComponent second];NSLog(@"year is: %d", year);NSLog(@"month is: %d", month);NSLog(@"day is: %d", day);NSLog(@"hour is: %d", hour);NSLog(@"minute is: %d", minute);NSLog(@"second is: %d", second);

14.读取plist文件

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];NSDictionary *dictionary = [[NSDictionary alloc]      initWithContentsOfFile:plistPath];    NSLog(@"config dictionary = %@",dictionary);

15.改变tabbar字体颜色,选中和未选中

 [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil] forState:UIControlStateNormal];

16.怎么在其他视图控制器中切换根视图控制器

WorkOrderListViewController *homePageViewController = [[WorkOrderListViewController alloc] init]; UIApplication *app =[UIApplication sharedApplication]; AppDelegate *app2 = app.delegate; app2.window.rootViewController = homePageViewController;

17.16进制颜色

#define UIColorFromRGBValue(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]UIColorFromRGBValue(0x7e7e7e);

18.多线程
这里写图片描述

19.跳转隐藏tabbar

/1.设置self.tabBarController.tabBar.hidden=YES;self.tabBarController.tabBar.hidden=YES;//2.如果在push跳转时需要隐藏tabBar,设置self.hidesBottomBarWhenPushed=YES;    self.hidesBottomBarWhenPushed=YES;    NextViewController *next=[[NextViewController alloc]init];    [self.navigationController pushViewController:next animated:YES];    self.hidesBottomBarWhenPushed=NO;//并在push后设置self.hidesBottomBarWhenPushed=NO;//这样back回来的时候,tabBar会恢复正常显示。

20.xib连线错误
报这个错,检查xib连线,是否有重复多连的
this class is not key value coding-compliant for the key XXX

21.tableview iOS 8自适应高度
这个新特性,意味着View被Autolayout调整frame后,会自动拉伸和收缩SupView。
具体到Cell,要求cell.contentView的四条边都与内部元素有约束关系。

在TableViewController里- (void)viewDidLoad {    [super viewDidLoad];//添加这两行代码    self.tableView.estimatedRowHeight = 44.0f;    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

22.cell复用
/* 类方法,返回cell /
+ (instancetype)cellWithTableView:(UITableView *)tableView {
static NSString *ReuseID = @“cell的id”;
InsurerListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseID];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@“cell类名” owner:self options:nil] lastObject];
}
return cell;
}

23.block遍历

enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {    }

24.edgesForExtendedLayout

self.edgesForExtendedLayout = UIRectEdgeNone;edgesForExtendedLayouttypedef NS_OPTIONS(NSUInteger, UIRectEdge) {    UIRectEdgeNone   = 0,    UIRectEdgeTop    = 1 << 0,    UIRectEdgeLeft   = 1 << 1,    UIRectEdgeBottom = 1 << 2,    UIRectEdgeRight  = 1 << 3,    UIRectEdgeAll    = UIRectEdgeTop | UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight} 

25 . 当前屏幕方向interfaceOrientation的获取

有3种方式可以获取到“当前interfaceOrientation”:

controller.interfaceOrientation,获取特定controller的方向[[UIApplication sharedApplication] statusBarOrientation] 获取状态条相关的方向[[UIDevice currentDevice] orientation] 获取当前设备的方向

25.SDWebimage

- setItem:(CustomItem *)item{    _item = item;  // 占位图片    UIImage *placeholder = [UIImage imageNamed:@"placeholderImage"];    // 从内存\沙盒缓存中获得原图    UIImage *originalImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.originalImage];    if (originalImage) { // 如果内存\沙盒缓存有原图,那么就直接显示原图(不管现在是什么网络状态)        [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];    } else { // 内存\沙盒缓存没有原图        AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];        if (mgr.isReachableViaWiFi) { // 在使用Wifi, 下载原图            [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];        } else if (mgr.isReachableViaWWAN) { // 在使用手机自带网络            //     用户的配置项假设利用NSUserDefaults存储到了沙盒中            //    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"alwaysDownloadOriginalImage"];            //    [[NSUserDefaults standardUserDefaults] synchronize];#warning 从沙盒中读取用户的配置项:在3G\4G环境是否仍然下载原图            BOOL alwaysDownloadOriginalImage = [[NSUserDefaults standardUserDefaults] boolForKey:@"alwaysDownloadOriginalImage"];            if (alwaysDownloadOriginalImage) { // 下载原图                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.originalImage] placeholderImage:placeholder];            } else { // 下载小图                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.thumbnailImage] placeholderImage:placeholder];            }        } else { // 没有网络            UIImage *thumbnailImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:item.thumbnailImage];            if (thumbnailImage) { // 内存\沙盒缓存中有小图                [self.imageView sd_setImageWithURL:[NSURL URLWithString:item.thumbnailImage] placeholderImage:placeholder];            } else {                [self.imageView sd_setImageWithURL:nil placeholderImage:placeholder];            }        }    }}

26.NSNumber转NSString可直接description

 NSString *status = [json[@"status"] description];

27.

// 主线程也会抽时间处理一下timer(不管主线程是否正在其他事件)    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

28.
自定义cell步骤

0 0
原创粉丝点击