ios-我常用的一些知识整理

1.tableView的分割线默认顶不到边,但有时我们需要顶到边。
#pragma mark - 分割线顶到边
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPat{
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
2.去掉多余cell
[self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
3.让cell选中时不变色
cell.selectionStyle = UITableViewCellSelectionStyleNone;
4.去掉指定行cell分割线
if (indexPath.row == 4) {
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
5.取消cell选中状态
[tableView deselectRowAtIndexPath:indexPath animated:YES]
6.cell动画出现效果
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CATransform3D rotation;
    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
    rotation.m34 = 1.0/ -600;
    cell.layer.transform = rotation;
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    [UIView setAnimationDuration:0.8];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];
    
    /*
     CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
     
     scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.2, 0.2, 1)];
     
     scaleAnimation.toValue  = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1, 1, 1)];
     
     scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
     
     [cell.layer addAnimation:scaleAnimation forKey:@"transform"];
     */
}
7.获取当前cell
   FirstCell *cell = (FirstCell *)[self.tableView cellForRowAtIndexPath:indexPath];
8.更新某个cell数据
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
9.cell点击完取消灰色背景
[tableView deselectRowAtIndexPath:indexPath animated:YES];
10.点击View,让键盘消失
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
11.拼音首字母排序
NSArray *resultArray = [_dataArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        
        return [obj1 compare:obj2 options:NSNumericSearch];
        
    }];
12.判断一个时间距离当前时间过去了多久
- (NSString *) compareCurrentTime:(NSString *)theTime
{
    //字符串转日期格式
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate=[format dateFromString:theTime];
    //有时差添加这个
    //NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    //NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    //NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    
    NSTimeInterval  timeInterval = [fromdate timeIntervalSinceNow];
    timeInterval = -timeInterval;
    long temp = 0;
    
    NSString *result;
    
    if (timeInterval < 60) {
        
        result = [NSString stringWithFormat:@"1分钟"];
        
    }else if((temp = timeInterval/60) <60){
        
        result = [NSString stringWithFormat:@"%ld分前",temp];
        
    }else if((temp = temp/60) <24){
        
        result = [NSString stringWithFormat:@"%ld小前",temp];
        
    }else if((temp = temp/24) <30){
        
        result = [NSString stringWithFormat:@"%ld天前",temp];
        
    }else if((temp = temp/30) <12){
        
        result = [NSString stringWithFormat:@"%ld月前",temp];
        
    }else{
        
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
        
    }
    
    return  result;
    
}
13.获取时间戳
//获取系统当前的时间戳
- (NSString *)getTime{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: dat];
    NSDate *localeDate = [dat  dateByAddingTimeInterval: interval];
    NSTimeInterval a=[localeDate timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];//转为字符型
    return timeString;
}
14.二进制转JSON
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
15.在AppDelegate中设置NavigationBar
if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
    //背景颜色
    [[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
   //设置字体颜色,font,大小
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont fontWithName:@ "HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
    
}
16.登陆时判断是不是手机号
//注册手机号判断
NSString *phoneRegex = @"1[3|5|7|8|][0-9]{9}";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
        
BOOL isMatch = [phoneTest evaluateWithObject:_phoneNumber.text];
if (isMatch) {
            
     NSLog(@"手机号正确");
            
}
17.判断邮箱正确?
-(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];
}
18.退出登陆后跳回主页
 [self.tabBarController setSelectedIndex:0]; 
 [self.navigationController popToRootViewControllerAnimated:YES];
19.设置底部标签栏背景
UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, W, 49)];
 backView.backgroundColor = BASECOLOR; 
[self.tabBarController.tabBar insertSubview:backView atIndex:0]; 
self.tabBarController.tabBar.opaque = YES;
20.设置导航栏不透明
self.navigationController.navigationBar.translucent = NO; 
self.tabBarController.tabBar.translucent = NO;
21.设置阴影
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)]; 
view.backgroundColor = [UIColor whiteColor]; 
view.layer.shadowOpacity = 0.8; 
view.layer.shadowOffset = CGSizeMake(1.0, 1.0); 
[self.view addSubview:view]; 
self.view.backgroundColor = [UIColor whiteColor];
22.跳转下一页,隐藏底部bar
- (void)nextBtnClicked:(UIButton *)btn{ 
  SetUpController *setVC = [[SetUpController alloc] init];
//隐藏底部状态栏 
  [setVC setHidesBottomBarWhenPushed:YES];       
  [self.navigationController pushViewController:setVC animated:YES];
}
23.发送通知,举个例子,用户登录成功,通知其他页面新用户登录
//登陆成功之后发起通知
   [[NSNotificationCenter defaultCenter] postNotificationName:@"此通知标识" object:nil];

//写在需要刷新数据的页面
  //注册通知
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:kNotificationIntrist object:nil];
 //在该页面删除通知
  - (void)dealloc{
     [[NSNotificationCenter defaultCenter]removeObserver:@"此通知标识"];
   }
24.block传值
 /*a页面.h代码*/
#import 
//评价完成刷新页面block
typedef void(^commentOverBlock)(BOOL reload);

@interface CommentController :UIViewController

@property (nonatomic,strong) commentOverBlock commentSuccessBlock;
- (void)returnCommentBlock:(commentOverBlock)block;

/*a页面.m代码*/

#import "CommentController.h"
@implementation CommentController
- (void)returnCommentBlock:(commentOverBlock)block{
    
    self.commentSuccessBlock = block;
}
#pragram mark - 评论完成执行方法
- (void)hadCommendSuccess{

    self.commentSuccessBlock(YES);
    
}

/*-------------------------------------------------------------------*/
/*b页面代码*/
CommentController *commentVC = [[CommentController alloc] init];
[commentVC returnCommentBlock:^(BOOL reload) {
        //刷新页面
 }];
25.字体导入
1.先下载需要的.ttf字体包,然后添加到项目中
2.在info.plist文件中添加Fonts provided by application字段,在该字段下,添加字体包名即可
26.全局token
//写入
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

[ud setObject:uid forKey:@"uid"];

[ud synchronize];

//取出
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];

NSString *uid = [ud objectForKey:@"uid"];
27.同时进行多个网络请求,两个请求都完成后执行下面操作
//信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    //创建全局并行
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //任务一
    dispatch_group_async(group, queue, ^{
        [self postRequest:^{ //这个block是此网络任务异步请求结束时调用的,代表着网络请求的结束.
            //一个任务结束时标记一个信号量
            dispatch_semaphore_signal(semaphore);
        }];
    });
    //任务二
    dispatch_group_async(group, queue, ^{
        [self postCommentListRequest:^{
            dispatch_semaphore_signal(semaphore);
        }];
    });
    
    dispatch_group_notify(group, queue, ^{
        
        // 三个请求对应三次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"ok啦,可以执行下面代码");
    });

- (void)postRequest:(void(^)())finish{
    
    VideoDetailViewModel *model = [[VideoDetailViewModel alloc] init];
    [model getModel:self.parametersModel videoDetailInfo:^(NSArray *array) {
        
        finish();
    } Failure:^(NSError *error) {
        
        finish();
    }];
}

- (void)postCommentListRequest:(void(^)())finish{
    
    VideoDetailViewModel *model = [[VideoDetailViewModel alloc] init];
    [model getModel:self.parametersModel ChatListModel:^(NSArray *array, BOOL haveMore) {
        
        finish();
    } Failure:^(NSError *error) {
        
        finish();
    }];
    
}
28.AFNetWorking设置返回json格式:
//设置请求返回格式数据为Json
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
29.AFNetWorking设置请求超时
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 15.f;
30.解析AFNetWorking返回error
NSLog(@"%@",[[NSString alloc] initWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);
31.Navgation返回指定页
UIViewController *viewCtl = self.navigationController.viewControllers[2];

    [self.navigationController popToViewController:viewCtl animated:YES];
32.tableview section header高度设置问题

这个应该是新手遇到的比较多的。起因是iOS奇葩的逻辑,如果你设置header(或者footer)高度是0的话,系统会认为你没设置,然后将其设置为40.f。所以需要将其设置为一个较小的数

_tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.001f)];

你可能感兴趣的:(ios-我常用的一些知识整理)