美文网首页
iOS代码笔记

iOS代码笔记

作者: 铁头娃_e245 | 来源:发表于2018-12-02 19:05 被阅读0次

0.达人笔记http://www.cocoachina.com/ios/20170626/19616.html

1.int和num互相转换

int a=[num intValue];

            shangpin.activity_type=[NSNumber numberWithInt: a];

2.隐藏tabbar

//进入下一页隐藏

self.hidesBottomBarWhenPushed=YES;

//一直隐藏

self.tabBarController.tabBar.hidden=YES;

3.回收键盘

//点击空白处回收键盘

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [super touchesBegan:touches withEvent:event];

    [self.view endEditing:YES];

}

//点击键盘的return回收键盘

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    [self.MoneyTextField resignFirstResponder];

    return YES;

}

4.寻找父视图

-(void)XiuGai:(UIButton *)button event1:(id)event200{

    UIView *v =[button superview];//获取父类view

    ShouHuoDZTableViewCell *cell=(ShouHuoDZTableViewCell *)[v superview];



    NSSet *touches =[event200 allTouches];

    UITouch *touch =[touches anyObject];

    CGPoint currentTouchPosition =[touch locationInView:self.tableView];

    NSIndexPath *indexPathxh1 =[self.tableView indexPathForRowAtPoint: currentTouchPosition];

    NSInteger zhi=indexPathxh1.row;

}

5.textView实现提示字

//placeHolder实现

    self.placeHolderView=[[UITextView alloc]initWithFrame:self.textView.frame];

    self.placeHolderView.font=self.textView.font;

    self.placeHolderView.text=@"说说哪里满意,帮大家选择";

    self.placeHolderView.textColor=[UIColor lightGrayColor];

6.button删除点击方法

[self.Button removeTarget:self action:@selector(Button:)forControlEvents:UIControlEventTouchUpInside];

7.UIActionSheet(调用相机,相册)

// 图片轻点的点击方法

-(void)tapAction:(UITapGestureRecognizer *)tap{

    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选取",nil];

    sheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;

    [sheet showInView:self.view];

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    //调用摄像头

    if(buttonIndex==0){

        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;

        if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])

        {

            UIImagePickerController *picker =[[UIImagePickerController alloc]init];

            picker.delegate = self;

            //设置拍照后的图片可被编辑

            picker.allowsEditing = YES;

            picker.sourceType = sourceType;

            [self presentModalViewController:picker animated:YES];

        }else

        {

            NSLog(@"模拟其中无法打开照相机,请在真机中使用");

        }

    }

    //调用相册

    if(buttonIndex==1){

        UIImagePickerController *picker=[[UIImagePickerController alloc]init];

        //设置代理人

        picker.delegate=self;

        //允许编辑

        picker.allowsEditing=YES;

        //模态进行跳转

        [self presentViewController:picker animated:YES completion:^{

        }];

    }

}

//点击choose触发

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    //跳回上一个界面

    [picker dismissViewControllerAnimated:YES completion:^{

    }];

    //图片信息通过info返回

    NSLog(@"%@",info);

    //从字典里提取info里的图片内容(选择图片的尺寸显示问题)

    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];

    self.XiuGaiImageView.image=image;

}

   UIActionView

UIAlertView *alertView =[[UIAlertView alloc]initWithTitle : @"故障信息" message : @"是否确定已经修理完毕阿萨德哈撒啥时候的金卡是大家稍等哈就是大师的金卡是打开时" delegate : nil cancelButtonTitle : @"确定" otherButtonTitles : nil];

    [alertView show];//展示

    [alertView dismissWithClickedButtonIndex:0 animated:YES];//收起

   UIAlertController

   UIAlertController * alertController =[UIAlertController alertControllerWithTitle: nil  message: @"请输入作物品种" preferredStyle:UIAlertControllerStyleAlert];

    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){

        textField.placeholder = @"name";

        textField.textColor =[UIColor blueColor];

        textField.clearButtonMode = UITextFieldViewModeWhileEditing;

        textField.borderStyle = UITextBorderStyleRoundedRect;

    }];

    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){

        textField.placeholder = @"password";

        textField.textColor =[UIColor blueColor];

        textField.clearButtonMode = UITextFieldViewModeWhileEditing;

        textField.borderStyle = UITextBorderStyleRoundedRect;

        textField.secureTextEntry = YES;

    }];

    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

        NSArray * textfields = alertController.textFields;

        UITextField * namefield = textfields[0];

        UITextField * passwordfiled = textfields[1];

        NSLog(@"%@:%@",namefield.text,passwordfiled.text);

    }]];

    [self presentViewController:alertController animated:YES completion:nil];

8.颜色渐变

//颜色渐变

    UIColor *colorOne =[UIColor colorWithRed:(19/255.0)  green:(66/255.0)  blue:(86/255.0)  alpha:0.5];

    UIColor *colorTwo =[UIColor colorWithRed:(55/255.0)  green:(132/255.0)  blue:(174/255.0)  alpha:1.0];

    NSArray *colors =[NSArray arrayWithObjects:(id)colorOne.CGColor,colorTwo.CGColor,nil];

    NSNumber *stopOne =[NSNumber numberWithFloat:0.0];

    NSNumber *stopTwo =[NSNumber numberWithFloat:1.0];

    NSArray *locations =[NSArray arrayWithObjects:stopOne,stopTwo,nil];



    _headerLayer =[CAGradientLayer layer];

    _headerLayer.colors = colors;

    _headerLayer.locations = locations;

    _headerLayer.frame = CGRectMake(0,300/667.0*HEIGHT,WIDTH,HEIGHT-300/667.0*HEIGHT);



    [self.view.layer insertSublayer:_headerLayer atIndex:0];

9.label计算高度

-(CGSize)sizeToFit:(UILabel *)label size:(CGSize)size{

    CGSize realSize =[label.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil].size;

    return realSize;

}

 数据.图片计算高度

#pragma mark设置tableView每行的高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    //在这个方法里,主要要计算图片的尺寸,来设置tableView的行高

    //找到图片和图片的尺寸

    UIImage *image=[UIImage imageNamed:self.picArr[indexPath.row]];

    NSLog(@"%g",image.size.height);

    //UIImage保存着实际图片的尺寸,而UIImageView是我们看见的图片的尺寸都通过它来设置

    //通过图片的实际尺寸和屏幕固定的宽进行等比例计算

    CGFloat rowHeight=self.view.frame.size.width*image.size.height/image.size.width;

    //计算文字的高度

    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName,nil];

    //根据文本的内容和文本的字体进行计算高度



    //参数1:告诉系统,文本显示的最大范围(尺寸)

    //参数2:枚举类型,告诉你当前的依据

    CGRect rect=[self.dataDic[@"JiShiPingLun"]boundingRectWithSize:CGSizeMake(self.view.frame.size.width,0)options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];



    //然后把图片的高和文字的高相加返回

    return rowHeight+rect.size.height;

}

10.KVC纠错方法

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

    if([key isEqualToString:@"id"]){

        self.shangpinID=value;

    }

}

11.避免cell重用

        ShangPinCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"shangpin" forIndexPath:indexPath];

#pragma mark避免重用

        while(cell.diview.subviews.lastObject != nil){

            [(UIView*)[cell.diview.subviews lastObject]removeFromSuperview];

        }

或者

static NSString *TableSampleIdentifier = @"TableSampleIdentifier";

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];

    if(cell == nil){

        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];



    }

12.通知相关

//添加通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gengxin2)name:@"jiajian2" object:nil];

//发送通知

[[NSNotificationCenter defaultCenter]postNotificationName:@"jiajian" object:nil userInfo:nil];

-(void)dealloc

{

    //dealloc方法里写移除观察者

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}

//如果传值

-(void)ButtonAction:(NSNotification *)notification{

    //NSLog(@"%@",notification.userInfo[@"index”]); 
}

13.键盘和文本框通知

// 键盘通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:)name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHide:)name:UIKeyboardWillHideNotification object:nil];

-(void)keyboardShow:(NSNotification *)notification {

    NSDictionary *info =[notification userInfo];

    int offset =[[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size.height;

    self.view.frame=CGRectMake(0,-offset+64,WIDTH,HEIGHT);

}

-(void)keyboardHide:(NSNotification *)notification{

    self.view.frame=CGRectMake(0,64,WIDTH,HEIGHT);

}

//方法2

//键盘弹起的时候触发的方法

-(void)keyboardHight:(NSNotification *)notification {

    NSDictionary *info =[notification userInfo];

    CGFloat keyHeight =[[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size.height;

    CGFloat maxY = CGRectGetMaxY(_koulingTextField.frame);

    CGFloat viewHeight = CGRectGetHeight(self.view.frame);

    CGFloat viewBottom = SCREEN_HEIGHT - CGRectGetMaxY(self.view.frame);

    CGFloat offset = -keyHeight + viewBottom + viewHeight-maxY;

    if(offset < 0){

        self.frame=CGRectMake(0,offset,SCREEN_WIDTH,SCREEN_HEIGHT);

    }

}

//文本框通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:)name:UITextFieldTextDidChangeNotification object:textField];

-(void)handleTextFqweieldTextDidChangeNotification:(NSNotification *)notification {

    UITextField *textField = notification.object;

    self.secureTextAlertAction.enabled = textField.text.length == 11;

}

14.时间戳

NSDate *currentDate =[NSDate date];//获取当前时间,日期

    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];

    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS"];

    NSString *dateString =[dateFormatter stringFromDate:currentDate];

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

NSInteger dis = 7;//前后的天数

                    NSDate* theDate;

                    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度

                    NSDateFormatter *dateFomatter =[[NSDateFormatter alloc]init];

                    dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

                    //截止时间data格式

                    NSDate *expireDate =[dateFomatter dateFromString:currentDate];

                    theDate =[expireDate initWithTimeIntervalSinceNow: +oneDay*dis];



                    //转化完成的时间数据转化为对应的时间格式

                    NSString * currentDateStr =[dateFomatter stringFromDate:theDate];

//时间差的简书

http://www.jianshu.com/p/3441101c89c0

15.配置包(安装包)
https://www.jianshu.com/p/20a705fe46f6
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

16.导航栏right按钮,返回按钮

//右按钮

    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"right相机.png"]style:UIBarButtonItemStyleDone target:self action:@selector(ClickReport)];

//或者(如果是文字)

UIBarButtonItem *myButton =[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(clickEvent)];

    self.navigationItem.rightBarButtonItem = myButton;

//返回按钮

UIBarButtonItem *backItem=[[UIBarButtonItem alloc]init];

    backItem.title=@"";

    backItem.tintColor=[UIColor whiteColor];

    self.navigationItem.backBarButtonItem = backItem;

    //隐藏返回键

    self.navigationItem.hidesBackButton = YES;

17.NSUserDefaults

//###存

        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];

        [defaults setObject:@"UserName" forKey:UserName];

        [defaults setInteger:10 forKey:@"Age"];



        UIImage *imageNS =image;

        NSData *imageData = UIImageJPEGRepresentation(imageNS,100);//把image归档为NSData

        [defaults setObject:imageData forKey:@"image"];



//###读



        NSUserDefaults *defaults1 =[NSUserDefaults standardUserDefaults];

        NSString *firstName1 =[defaults1 objectForKey:@"UserName"];

        NSInteger age =[defaults1 integerForKey:@"Age"];



        NSData *imageData1 =[defaults1 dataForKey:@"image"];

        UIImage *image1 =[UIImage imageWithData:imageData1];

NSUserDefaults支持的数据类型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL.

//删除

[[NSUserDefaults standardUserDefaults]removeObjectForKey:@"isFirst"];

18.WebView

[webView setScalesPageToFit:YES];解决webView适配问题

//webkit解决适配问题(初始化要用[UIScreen mainScreen].bounds.size)

WKWebView *webView =[[WKWebView alloc]initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height-64)];

19.PCH

预编译头文件

1  创建

Com + N  -> Other  -> PCH File

2  链接到Build Settings中

      中搜索prefix,在倒数第二个中的prefix Header,

双击后面的空白处,把创建的PCH文件拖到这个框中,出来一个路径

3 修改为虚拟路径

   添加 $(SRCROOT),添加的位置不一定在哪里,但是只要回车就会出现一个路径,只要这个路径和之前的绝对路径一致就行,不一致就看着删除或者添加一两个文件就行..

4  缺点,Com + B的时候都会编译一遍pch  ,所以会很慢

20.AttributedString(博客:http://www.cnblogs.com/chaochaobuhuifei55/p/5253022.html)

NSString *str=@"150元";

    NSMutableAttributedString * attriStr=[[NSMutableAttributedString alloc]initWithString:str];

    NSRange range =[str rangeOfString:@"150"];

    [attriStr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:range];

    NSRange range1 =[str rangeOfString:@"元"];



    [attriStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:114/255.00 green:134/255.00 blue:178/255.00 alpha:1]} range:range1];

    laber1.attributedText = attriStr;

21.强制切换横竖屏

[[UIDevice currentDevice]setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight]forKey:@"orientation"];

22.单行刷新

NSIndexPath *indexpath =[NSIndexPath indexPathForItem:index  inSection:0];

[self.tableView reloadRowsAtIndexPaths:@[indexpath]withRowAnimation:UITableViewRowAnimationAutomatic];

23.将图片存至相册(也可用于截屏获取图片)

UIGraphicsBeginImageContext(_drawer.bounds.size);

[_drawer.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageWriteToSavedPhotosAlbum(viewImage,nil,nil,nil);

23.定时器

//脏timer

    //scheduledTimerWithTimeInterval创建出来的timer默认里边已经有RunLoop

//    NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timer)userInfo:nil repeats:YES];

//正经的timer纯洁的!

NSTimer *timer=[NSTimer timerWithTimeInterval:3 target:self selector:@selector(scrollNext)userInfo:nil repeats:YES];

    //问题:定时器不一定准确

    //因为苹果的RunLoop导致的,当定时器加到scrollview或者继承scrollview的空间时,当滑动空间scrollview的时候,定时器会暂停

    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

-(void)removetimer{

    //停止定时器

    [self.myTimer invalidate];

    //定时器置空

    self.myTimer=nil;

}

24.隐藏导航栏, 导航栏透明

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES animated:YES];

}

-(void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

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

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //导航栏透明
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    //字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:HYUniTextcor1, NSFontAttributeName:[UIFont systemFontOfSize:HY_SIZE1]}];   
}

25.模态跳转

LoginViewController *secVC=[[LoginViewController alloc]init];

    [secVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];

    [self presentViewController:secVC animated:YES completion:^{



    }

 ];

//返回

[self dismissViewControllerAnimated:YES completion:^{



    }];

26.改变可变数组里一个字典的值

NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithDictionary:self.dataArr[index]];

    dic[@"shu"]=@"2";

    self.dataArr[index]=dic;

27.获取到URL加载后的image

self.image =[[SDImageCache sharedImageCache]imageFromDiskCacheForKey:image];

28.上传图片到后台

AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];

        NSString *url=@"http://www.yangzhuokeji.com/owo/index.php/Home/My/headd";

        NSDictionary *dic=@{@"lianxi":@"1"};

        [manager POST:url parameters:dic constructingBodyWithBlock:^(id _Nonnull formData){



            NSData *imageData =UIImageJPEGRepresentation(self.image,1);



            NSDateFormatter *formatter =[[NSDateFormatter alloc]init];

            formatter.dateFormat =@"yyyyMMddHHmmss";

            NSString *str =[formatter stringFromDate:[NSDate date]];

            NSString *fileName =[NSString stringWithFormat:@"%@.jpg",str];



            //上传的参数(上传图片,以文件流的格式)

            [formData appendPartWithFileData:imageData

                                        name:@"file"

                                    fileName:fileName

                                    mimeType:@"image/jpeg"];



        } progress:^(NSProgress *_Nonnull uploadProgress){

            //打印下上传进度

        } success:^(NSURLSessionDataTask *_Nonnull task,id _Nullable responseObject){

            //上传成功

            NSLog(@"%@",responseObject);

        } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nonnull error){

            //上传失败

            NSLog(@"--------%@",error);

        }];

29.一个NSString全局调用

//.h里写,放在pch里

NSString * const URL = @"23426357689";

extern NSString * const URL;   

30.毛玻璃

UIBlurEffect *effect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];

    UIVisualEffectView *view=[[UIVisualEffectView alloc]initWithEffect:effect];

    view.alpha=0.1;

    view.frame=CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height);

    [self.view addSubview:view];

31.改变button图片的位置

lianxikefu.imageEdgeInsets = UIEdgeInsetsMake(10,0,0,0);

32.POST上传字符串字典

/*!

 * @brief把格式化的JSON格式的字符串转换成字典

 * @param jsonString JSON格式的字符串

 * @return返回字典

 */

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

    if(jsonString == nil){

        return nil;

    }

    NSData *jsonData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *err;

    NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:jsonData

                                                        options:NSJSONReadingMutableContainers

                                                          error:&err];

    if(err){

        NSLog(@"json解析失败:%@",err);

        return nil;

    }

    return dic;

}

//词典转换为字符串

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{

    NSError *parseError = nil;

    NSData *jsonData =[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

    return[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

}

//数组转化为字符串

NSString *str1 =[arr componentsJoinedByString:@","];

33.其他视图控制器中转换根视图控制器

http://blog.csdn.net/lc_obj/article/details/17305353

34.布局出现莫名其妙的问题

self.edgesForExtendedLayout = UIRectEdgeNone;

//在进入当前controller的时候,找第一个响应的scrollView,然后给这个是scrollview一个inset(上,左,下,右)偏移

self.automaticallyAdjustsScrollViewInsets = NO;

35.对输入框的判断

if([lingQuJuLiTextField.text integerValue]>1000){

        lingQuJuLiTextField.text =[lingQuJuLiTextField.text substringToIndex:lingQuJuLiTextField.text.length-1];

//

Boolean isHaveDian;

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    if(textField.keyboardType == UIKeyboardTypeDecimalPad){

        if([textField.text rangeOfString:@"."].location==NSNotFound){

            isHaveDian=NO;

        }

        if([string length]>0)

        {

            unichar single=[string characterAtIndex:0];//当前输入的字符

            if((single >='0' && single<='9')|| single=='.')//数据格式正确

            {

                //首字母不能为0和小数点

                if([textField.text length]==0){

                    if(single == '.'){

                        //                    [self alertView:@"亲,第一个数字不能为小数点"];

                        [textField.text stringByReplacingCharactersInRange:range withString:@""];

                        return NO;
                    }

                }else if(textField.text.length == 1 &&[textField.text isEqualToString:@"0"]){

                    if(single != '.'){

                        //                    [self alertView:@"亲,第一个数字不能为0"];

                        //[textField.text stringByReplacingCharactersInRange:NSMakeRange(0,1)withString:@""];

                        textField.text = string;

                        return NO;

                    }

                }

                if(single=='.')

                {

                    if(!isHaveDian)//text中还没有小数点

                    {

                        isHaveDian=YES;

                        return YES;

                    }else

                    {

                        //                    [self alertView:@"亲,您已经输入过小数点了"];

                        [textField.text stringByReplacingCharactersInRange:range withString:@""];

                        return NO;

                    }

                }

                else

                {

                    if(isHaveDian)//存在小数点

                    {

                        //判断小数点的位数

                        NSRange ran=[textField.text rangeOfString:@"."];

                        NSInteger tt=range.location-ran.location;

                        if(tt <= 2){

                            return YES;

                        }else{

                            //                        [self alertView:@"亲,您最多输入两位小数"];

                            return NO;

                        }

                    }

                    else

                    {

                        return YES;

                    }

                }

            }else{//输入的数据格式不正确

                //            [self alertView:@"亲,您输入的格式不正确"];

                [textField.text stringByReplacingCharactersInRange:range withString:@""];

                return NO;

            }

        }

        else

        {

            return YES;

        }

    }

    return YES;

36:初始化tableViewCell方法

-(UITableViewCell *)__cellFromClass:(Class)aClass {

    NSString *cellID = NSStringFromClass(aClass);

    UINib *nib =[UINib nibWithNibName:cellID bundle:nil];

    [self.tableView registerNib:nib forCellReuseIdentifier:cellID];

    UITableViewCell *cell =[self.tableView dequeueReusableCellWithIdentifier:cellID];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.backgroundColor =[UIColor whiteColor];

    return cell;

}

37:字符串的使用

NSRange rangeR=[str rangeOfString:@"."];

    NSString *strR=[str substringToIndex:rangeR.location];

38.换root,登录到主页,引用AppDelegate.h  可以调用里面的方法,如runHome

//登录到主界面

 [(AppDelegate *)[UIApplication sharedApplication].delegate runHome];

39.主视图上添加子视图(一般用于视图上添加封装的view)

[[UIApplication sharedApplication].keyWindow addSubview:self];

40.几种block使用

第一种:

@property(nonatomic,copy)void(^newblock)(NSString *);  //.h

self.newblock(self.textField.text);  //.m

void(^newblock)(NSString *)=^(NSString *str){

        //参数只有在block里有用

        NSLog(@"%@",str);

    };

    vc.newblock=newblock;  //上一页

第二种:

-(void)show:(NSArray *)jsonArr doSelectBlock:(RaindropViewBlock)block;

/**回调方法*/

typedef void(^RaindropViewBlock)(NSDictionary *dic);    //.h

@property(strong,nonatomic)RaindropViewBlock raindropViewBlock;   

if(self.raindropViewBlock){

                self.raindropViewBlock(_jsonArr[I]);

}    //.m

第三种:

+(void)openWithRedInfo:(NSDictionary *)redInfoDict success:(void(^)(NSDictionary *redInfo))success;

if(success){

                    success(redInfo);

 }

//解决循环引用

__weak UIViewController *weakSelf = self;

41.最上层视图 判断是否有到导航栏

[self.navigationController visibleViewController].navigationController.navigationBarHidden == NO

43.collectionView协议方法

/**

 *  当点击item时会调用此方法 在此方法中把点击的item的textLabel属性的字体颜色和边框改变颜色

 */

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

JWCCollectionViewCell *cell =(JWCCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

cell.textLabel.textColor =[UIColor redColor];

cell.textLabel.layer.borderColor =[UIColorredColor].CGColor;

}

44.直接返回使用的cell高度(可以在cell动态写高度)

UITableViewCell *cell =[self tableView:tableView cellForRowAtIndexPath:indexPath];

return cell.frame.size.height;

45.测试坐标

//    x = @"14554655.09654828";

//    y = @"6034730.463003586";

46.AFNetworking请求崩溃提示Invalid parameter not satisfying: URLString(可能是含中文  需要转义)

url =[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

47.无线后台

-(void)applicationDidEnterBackground:(UIApplication *)application {

    // Use this method to release shared resources,save user data,invalidate timers,and store enough application state information to restore your application to its current state in case it is terminated later.

    // If your application supports background execution,this method is called instead of applicationWillTerminate: when the user quits.

    //允许后台任务

    UIApplication *app =[UIApplication sharedApplication];

    //__block UIBackgroundTaskIdentifier bgTask;

    //@property(nonatomic,assign)UIBackgroundTaskIdentifier bgTask;

    self.bgTask =[app beginBackgroundTaskWithExpirationHandler:^{

        dispatch_async(dispatch_get_main_queue(),^{

            if(self.bgTask != UIBackgroundTaskInvalid){

                self.bgTask = UIBackgroundTaskInvalid;

            }

        });

    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{

        dispatch_async(dispatch_get_main_queue(),^{

            if(self.bgTask != UIBackgroundTaskInvalid){

                self.bgTask = UIBackgroundTaskInvalid;

            }

        });

    });

}

-(void)applicationWillEnterForeground:(UIApplication *)application {

    // Called as part of the transition from the background to the inactive state;here you can undo many of the changes made on entering the background.

    //结束后台任务

    UIApplication *app =[UIApplication sharedApplication];

    [app endBackgroundTask:self.bgTask];

    dispatch_queue_t mainQueue = dispatch_get_main_queue();

    dispatch_async(mainQueue,^{

        if(self.bgTask != UIBackgroundTaskInvalid){

            self.bgTask = UIBackgroundTaskInvalid;

        }

    });

}

48:AF3.0下载

NSURL *url =[NSURL URLWithString:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"];

    //默认配置

    NSURLSessionConfiguration *coufiguration =[NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager =[[AFURLSessionManager alloc]initWithSessionConfiguration:coufiguration];

    NSURLRequest *request =[NSURLRequest requestWithURL:url];
//加header的request
//NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] 
//requestWithMethod:@"GET" URLString:url parameters:nil error:nil];

    [request setValue:@"src.hjq.komect.com" forHTTPHeaderField:@"Host"];

    NSURLSessionDownloadTask *task =[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress){

// @property int64_t totalUnitCount;  需要下载文件的总大小

// @property int64_t completedUnitCount;当前已经下载的大小

        //给Progress添加监听KVO

        NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

        //回到主队列刷新UI进度条

        dispatch_async(dispatch_get_main_queue(),^{

        });

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath,NSURLResponse * _Nonnull response){

        NSString *cachesPath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];

        NSString *path =[cachesPath stringByAppendingPathComponent:response.suggestedFilename];

        return[NSURL fileURLWithPath:path];

    } completionHandler:^(NSURLResponse * _Nonnull response,NSURL * _Nullable filePath,NSError * _Nullable error){

        // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用

        NSString *imgFilePath =[filePath path];//将NSURL转成NSString

        NSLog(@"is a filePath---->>%@",imgFilePath);

    }];

    [task resume];

49.跳转到App Store(把里面的XXX替换成你自己的APP ID)

-(void)goToAppStore

{

    NSString *itunesurl = @"itms-apps://itunes.apple.com/cn/app/idXXXXXX?mt=8&action=write-review";

    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:itunesurl]];

}

50.火星坐标转换

CLLocation * marsLoction =  [location locationMarsFromEarth];

51.输入金额限制

if(TextField.text.floatValue > Label.text.floatValue){

            textField.text =[textField.text substringToIndex:textField.text.length-1];

            [ProgressHUD showErrorStatus:@"绝产面积不能大于保险面积!"];

            return;

        }

52.对xib更换副视图要对View操作而不是对layer操作  在视图里拖控件  而不是在列表选控件

53.当需要刷新布局时,用setNeedsLayOut方法;当需要重新绘画时,调用setNeedsDisplay方法。还有layoutIfNeeded方法

[UIView animateWithDuration:duration animations:^{

        _sendViewBottom.constant = rect.size.height;

        [self.view layoutSubviews];

    }];

[UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {

    }];

54.隐藏导航栏返回按钮文字

//将返回按钮的文字position设置不在屏幕上显示UIOffsetMake(NSIntegerMin,NSIntegerMin)

[[UIBarButtonItem appearance]setBackButtonTitlePositionAdjustment:UIOffsetZero forBarMetrics:UIBarMetricsDefault];

55.导航栏渐变
#pragma mark --------移动就触发的方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffest=self.scroll.contentOffset.y;
    if (self.scroll.contentOffset.y > 0) {
        headView.frame = CGRectMake(0, -yOffest, SCREEN_WIDTH, 180*Resolution_Ratio);
        accelerateButton.frame = CGRectMake(12*Resolution_Ratio, 160*Resolution_Ratio-yOffest, SCREEN_WIDTH-24*Resolution_Ratio, 40*Resolution_Ratio);
        
        //计算透明度,90为随意设置的偏移量临界值
        CGFloat alpha = scrollView.contentOffset.y/90.0f >0.99 ? 0.99:scrollView.contentOffset.y/90.0f;
        NSLog(@"透明度:%f",alpha);
        //设置一个颜色并转化为图片
        UIImage *image = [self imageWithColor:[UIColor colorWithRed:92.f/255 green:218.f/255 blue:232.f/255 alpha:alpha]];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
    }
}

56.将颜色转换为图片image
- (UIImage *)imageWithColor:(UIColor *)color {
    //创建1像素区域并开始图片绘图
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    
    //创建画板并填充颜色和区域
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    //从画板上获取图片并关闭图片绘图
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

57.GCD异步请求2个网络请求
dispatch_group_t group =  dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        dispatch_group_enter(group);   //标志着一个任务追加到 group,执行一次,相当于 group 中未执行完毕任务数+1
        WEAKSELF
        [[HYRuleEngine sharedEngine] getRulesByDevice:nil isDetail:YES success:^(HYZYRulesResultModel *model) {
            STRONGSELF
            strongSelf.linkworkList = model.siddhiRules;
            dispatch_group_leave(group);   //标志着一个任务离开了 group,执行一次,相当于 group 中未执行完毕任务数-1
        } failure:^(NSError *error) {
            dispatch_group_leave(group);    //如果请求失败,未执行完毕任务数也-1
        }];
    });

    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务2
        dispatch_group_enter(group);   //group 中未执行完毕任务数+1
        WEAKSELF
        [[HYRuleEngine sharedEngine] getRecommendedSiddhiRulesZiYanSuccess:^(HYZYRulesResultModel *model) {
            STRONGSELF
            strongSelf.recommendSceneList = [NSArray arrayWithArray:model.siddhiRules];
            dispatch_group_leave(group);    //如果请求成功,未执行完毕任务数-1
        } failure:^(NSError *error) {
            dispatch_group_leave(group);    //如果请求失败,未执行完毕任务数也-1
        }];
    });

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步任务1、任务2都执行完毕后,回到主线程执行下边任务
        [self.tableView reloadData];
    });

58.GCD倒计时
__block NSInteger time = 59; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                weakSelf.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(weakSelf.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(weakSelf.timer, ^{
                    if(timeout<=60){ //倒计时结束,关闭
                        if (timeout<=0) {
                            dispatch_source_cancel(weakSelf.timer);
                            dispatch_async(dispatch_get_main_queue(), ^{
                                //设置界面的按钮显示 根据自己需求设置
                                [self.navigationController popViewControllerAnimated:YES];
                            });
                        }
                    }else{
                        int hour = timeout / 3600;
                        int minute = timeout / 60 % 60;
                        int second = timeout % 60;
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            self.timerLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d",hour,minute,second];
                        });
                        timeout -= 1;
                    }
                });
                dispatch_resume(weakSelf.timer);

59.对比时间差(根据服务器指定的格式选择方案)
①第一种
    NSString *redEffectiveTime = @"2017-7-1 9:47:00";
    
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    // 截止时间字符串格式
    NSString *expireDateStr = redEffectiveTime;
    // 当前时间字符串格式
    NSString *nowDateStr = [dateFomatter stringFromDate:nowDate];
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:expireDateStr];
    // 当前时间data格式
    nowDate = [dateFomatter dateFromString:nowDateStr];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
    
    NSString *day = [NSString stringWithFormat:@"%d",(int)dateCom.day];
    NSString *hours = [NSString stringWithFormat:@"%02d",(int)dateCom.hour];
    NSString *minutes = [NSString stringWithFormat:@"%02d",(int)dateCom.minute];
    NSString *seconds = [NSString stringWithFormat:@"%02d",(int)dateCom.second];
    
    NSString *time = @"";
    if ([day intValue]>0) {
        time = [NSString stringWithFormat:@"剩余时间:%@天%@:%@:%@",day,hours,minutes,seconds];
    }else{
        time = [NSString stringWithFormat:@"剩余时间:%@:%@:%@",hours,minutes,seconds];
    }
②第二种
HYRuleModel *tempModel = self.countdownModel;
    NSString* desc = [HYTimerRuleEngine displayStringWithcronString:tempModel.schedule];
    NSArray* arr = [desc componentsSeparatedByString:@" "];    //得到12:27
    NSArray *tempArr = [[arr safeObjectAtIndex:0] componentsSeparatedByString:@":"];  //得到12 和 27
    NSString* hour = [tempArr safeObjectAtIndex:0];
    NSString* min = [tempArr safeObjectAtIndex:1];
    int mins = [hour intValue]*3600+[min intValue]*60;
    
    //得到当前时间
    NSDate* nowDate = [NSDate date];
    NSTimeZone* zone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSTimeInterval time = [zone secondsFromGMTForDate:nowDate];// 以秒为单位返回当前时间与系统格林尼治时间的差
    int newTime = ([nowDate timeIntervalSince1970]+time);
    int nowhour = newTime / 3600;
    int nowminite = newTime / 60 % 60;
    int newsecond = newTime % 60;
    nowhour %= 24;
    newTime = 3600*nowhour+60*nowminite+newsecond;
    
    __block int timeout = mins-newTime; //倒计时时间

60.edgesForExtendedLayout理解
https://blog.csdn.net/yz_lby/article/details/46739087
拿UIScrollView来举例,在含有导航栏的页面内, self.edgesForExtendedLayout = UIRectEdgeNone; 调整的是UIScrollView本身的位置,self.automaticallyAdjustsScrollViewInsets = NO;调整的是UIScrollView显示内容的位置。
在iOS7之后self.edgesForExtendedLayout 默认值UIRectEdgeAll,此时坐标原点在屏幕左上角 ,在设置self.edgesForExtendedLayout = UIRectEdgeNone 会使坐标原点在导航栏左下角也就是说坐标原点回和iOS6一样,从这点来说设置self.edgesForExtendedLayout = UIRectEdgeNone达到的效果和设置
self.navigationController.navigationBar.translucent = NO效果一样。 self.edgesForExtendedLayout = UIRectEdgeNone是会对整个页面的控件的坐标起到作用的,而self.automaticallyAdjustsScrollViewInsets = NO 是只针对于UIScrollView的。

61.贝塞尔设置单边圆角
- (void)cfgCornorRadious:(UIView*)view{
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(4, 4)];
    CAShapeLayer * layer = [[CAShapeLayer alloc]init];
    layer.frame = view.bounds;
    layer.path = path.CGPath;
    view.layer.mask = layer;
}

62.model和父类共用属性
@synthesize description = _description;   //和父类共用属性   重写了set方法

63.将中文字符串转换为拼音格式(不带声调)
- (NSString *)transformToPinyin:(NSString *)str
{
    // 空值判断
    if (str == nil || str == NULL) {
        return @"";
    }
    // 将字符串转为NSMutableString类型
    NSMutableString *string = [str mutableCopy];
    // 将字符串转换为拼音音调格式
    CFStringTransform((__bridge CFMutableStringRef)string, NULL, kCFStringTransformMandarinLatin, NO);
    // 去掉音调符号
    CFStringTransform((__bridge CFMutableStringRef)string, NULL, kCFStringTransformStripDiacritics, NO);
    // 返回不带声调拼音字符串
    return string;
}

64.获取最上层视图控制器
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}
- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}


相关文章

网友评论

      本文标题:iOS代码笔记

      本文链接:https://www.haomeiwen.com/subject/dnucbftx.html