• iOS 一些常用方法笔记


    全局引用:
    BOOL state
    其他地方:extern BOOL state;
    两种特例:
    @synthesize id=_id;
    @synthesize descriptoin=_description;
    _和self的区别:
    有setter和getter方法(@property(nomatic ,passion) UIView *view)时,两者堵可以,
    当只是属性({   e.g.: UIView *_view  })时,只能”_”


    retain 是指针拷贝,copy 是内容拷贝。
    通过@synthesize 指令告诉编译器在编译期间产生getter/setter方法。 2:通过@dynamic指令,自己实现方法。
    位置请求授权:NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription


    1.mrc.arc 混编:
    2.mrc下编译环境下使用arc  -fobjc-arc
    反之 :-fno-objc-arc
    3.init 方法,初始化和shared方法
    4.要想在block块内使用局部变量,需要在block外加上”__block 变量名"
    5.
    1. //获取应用程序沙盒的Documents目录      NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);  
    2.     NSString *plistPath1 = [paths objectAtIndex:0]; 
    3.      
    4.     //得到完整的文件名 
    5.     NSString *filename=[plistPath1 stringByAppendingPathComponent:@"test.plist"]; 
    6.    //输入写入 
    7.     [data writeToFile:filename atomically:YES]; 
    8.      
    9.     //那怎么证明我的数据写入了呢?读出来看看 
    10.     NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename]; 
    11.     NSLog(@"%@", data1);    
    12.
    13.
    14. @(20):这表示一个对象
    15. 抽象类:用来派生子类
    16. #define  如果定义太长 在换行时加“”
    17. frame指的是:该view在父view坐标系统中的位置和大小。(参照点是父亲的坐标系统)bounds指的是:该view在本身坐标系统中 的位置和大小。(参照点是本身坐标系统)
    18. 重绘 setNeedsDisplay,调用drawrect, 刷新布局: setNeedsLayout,调用 layoutSubViews,

    调用定位时在target里设置两个属性:NSLocationAlwaysUsageDescription  NSLocationWhenInUseUsageDescription
    Xcode升级后不支持http访问的解决办法:在Info.plist中添加NSAppTransportSecurity类型Dictionary。
        在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES

    1、 发送短信
     // 如果利用该方式发送短信, 当短信发送完毕或者取消之后不会返回应用程序
    //        NSURL *url = [NSURL URLWithString:@"sms://10010"];
    //        [[UIApplication sharedApplication] openURL:url];
            
            // 判断当前设备能否发送短信
            if (![MFMessageComposeViewController canSendText]) {
                NSLog(@"当前设备不能发送短信");
                return ;
            }
            
            MFMessageComposeViewController *vc = [[MFMessageComposeViewController alloc] init];
            // 设置短信内容
            vc.body = @"吃饭了没?";
            // 设置收件人列表
            vc.recipients = @[@"10010"];
            // 设置代理
            vc.messageComposeDelegate = self;
            // 显示控制器
            [self presentViewController:vc animated:YES completion:nil];

    2. 打电话

            // 弊端:使用该方法进行拨号之后,当电话挂断之后不会返回应用程序, 会停留在通话记录界面
    //        NSURL *url = [NSURL URLWithString:@"tel://13261936021"];
    //        [[UIApplication sharedApplication] openURL:url];
            
            // 在拨打电话之后会提示用户是否拨打, 当电话挂断之后会返回应用程序
    //        NSURL *url = [NSURL URLWithString:@"telprompt://13261936021"];
    //        [[UIApplication sharedApplication] openURL:url];

     3. 冒泡排序算法

    for (i = 0; i < length - 1; ++i)// 趟次  

        {  

            for (j = i + 1; j < length; ++j)  

            {  

                if (arr[i] > arr[j])  

                {  

                    tmp = arr[i];  

                    arr[i] = arr[j];  

                    arr[j] = tmp;  

                }  

            }  

        } 

    4.  图片从中间拉伸
    // 左端盖宽度
        NSInteger leftCapWidth = bgImage.size.width * 0.5f;
        // 顶端盖高度
        NSInteger topCapHeight = bgImage.size.height * 0.5f;
        
        bgImage = [bgImage stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];

    5.弹出动画
    //出厂动画
    - (void)animationWith:(UIView *)view
    {
        
        CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        animation.duration = 0.5;
        
        NSMutableArray *values = [NSMutableArray array];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
        [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
        animation.values = values;
        [view.layer addAnimation:animation forKey:nil];
        
        
    }

    6.经常容易出错的和遗漏的地方
        设置tag值时必须大于100,  tableView 的头尾高度 不能设置为0.。可以是0.001
    7.
    处理键盘弹出事件, 调整搜索框的高度
      -(void)registNoti{

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

        

    }

    // 键盘显示
    -(void) shown:(NSNotification*) notification
    {
        // keyboardFrame
        CGRect initialFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        
        CGRect convertedFrame = [self.view convertRect:initialFrame fromView:nil];
        
        CGRect tvFrame = self.infoTabaleView.frame ;
        tvFrame.size.height = convertedFrame.origin.y - 60;
        self.infoTabaleView.frame = tvFrame ;
        
    }

    // 键盘隐藏
    -(void) keyboardHidden:(NSNotification*) notification
    {
        CGRect tvFrame = self.infoTabaleView.frame;
        tvFrame.size.height = _initialTVHeight;
        self.infoTabaleView.frame = tvFrame;
    }


    清理缓存
    UIAlertView * alert =[ [UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除缓存" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        
        NSString * documentPath =[NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
        NSLog(@"%@",documentPath);
        BOOL isDataExist=[[NSFileManager defaultManager]fileExistsAtPath:documentPath];
        NSLog(@"~~~~~~~%d",isDataExist);
        if (isDataExist)
        {
            long long content=[[[NSFileManager defaultManager]attributesOfItemAtPath:documentPath error:nil]fileSize];
            float size=content/1024.0;
            NSString * content2 = [NSString stringWithFormat:@"%.2fMB",size];
            alert.message = [@"是否删除缓存" stringByAppendingString:content2];
            [ [NSFileManager defaultManager]removeItemAtPath:documentPath error:nil];
            [alert show] ;
        }
        else
        {
            alert.message = @"暂无缓存";
            [alert show];
        }

    图片裁剪: 比如星际显示的时候:
     starImageView.contentMode=UIViewContentModeLeft;
        //设置剪裁
        starImageView.clipsToBounds=YES;
        float x=65/5.0*num;
        starImageView.frame=CGRectMake(0, 0, x, 23);

    判断版本号:
     NSString *key = @"CFBundleVersion";
        
        // 取出沙盒中存储的上次使用软件的版本号
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *lastVersion = [defaults stringForKey:key];
        
        // 获得当前软件的版本号
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
        
        if ([currentVersion isEqualToString:lastVersion]) {
            // 显示状态栏
          
        } else { // 新版本
            [defaults setObject:currentVersion forKey:key];
            [defaults synchronize];
        }


    根据颜色得到图片
    - (UIImage *)imageWithColor:(UIColor *)color
    {
        CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, rect);
        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return image;
    }
    // 得当前View上的图片
    + (UIImage *)captureImageWithView:(UIView *)view
    {
        // 1.创建bitmap上下文
        UIGraphicsBeginImageContext(view.frame.size);
        // 2.将要保存的view的layer绘制到bitmap上下文中
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
        // 3.取出绘制号的图片
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        return newImage;
    }

    1.修改复制粘贴显示英文
    /*
     如何修改系统语言显示英文(复制,粘贴)
     解决办法是用vim直接打开工程的Info.plist文件,在文件中增加如下内容即可
     <key>CFBundleLocalizations</key>
     <array>
            <string>zh_CN</string>
            <string>en</string>
     </array>
     
     */
    另一种方式:修改Info.plist文件的Localization native development region属性值为China
    2.图片压缩
     + (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
      {
      // Create a graphics image context
      UIGraphicsBeginImageContext(newSize);
      // Tell the old image to draw in this new context, with the desired
      // new size
      [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
      // Get the new image from the context
      UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
      // End the context
      UIGraphicsEndImageContext();
      // Return the new image.
      return newImage;
      }
    3.javascript
        //<1>获取当前页面的url
        NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
        NSLog(@"currentURL = %@",currentURL);
        
        //<2>获取当前界面的title
        NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        NSLog(@"title = %@",title);

    4.  程序启动时每次收到推送 或 程序未启动通过推送消息启动程序时,都将会触发appdelegate里面的方法(注意要跟服务器的证书一直,比如开发环境,服务器也要用开发证书的pem才行):
    - ( void )application:( UIApplication *)application didReceiveRemoteNotification:( NSDictionary *)userInfo
    {
    //////////这里是收到推送后的逻辑代码
    // 需要  #import <AudioToolbox/AudioToolbox.h>
    AudioServicesPlaySystemSound (1007); //系统的通知声音
    AudioServicesPlayAlertSound ( kSystemSoundID_Vibrate );//震动
    //自定义声音
    NSString *path = [[ NSBundle mainBundle ] pathForResource : @"message" ofType : @"wav" ];
    // 组装并播放音效
    SystemSoundID soundID;
    NSURL *filePath = [ NSURL fileURLWithPath :path isDirectory : NO ];
    AudioServicesCreateSystemSoundID (( __bridge CFURLRef )filePath, &soundID);
    AudioServicesPlaySystemSound (soundID);
    // 声音停止
    AudioServicesDisposeSystemSoundID (soundID);
    }
    *         userInfo默认包含以下内容:
    aps =  {
    alert = "";//推送显示的问题信息在这里
    badge = 0;//app的icon右上角的推送数字 在这里设置
    sound = "";
    };
    *         如果需要添加自定义的字段,就让服务器的小伙伴们 跟aps同一层级添加一个数组(以Json为例):
    {
    "aps" : { "alert" : "This is the alert text", "badge" : 1, "sound" : "default" },
    "server" : { "serverId" : 1, "name" : "Server name")
    }
    这样收到的
    userInfo里面会多一个server的字段。

  • 相关阅读:
    idea 安装lombok 插件过程
    typora快捷键之速成笔记
    Android端抓取日志
    接口测试Case之面向页面对象编写及规范
    Jenkins + jmeter + ant + git 自动化集成
    自动化测试使用流程
    Jenkins git 的配置及问题解决
    传智springMVC笔记
    session 原理 数据结构
    Redis 3.0 集群搭建
  • 原文地址:https://www.cnblogs.com/blogfan/p/5534987.html
Copyright © 2020-2023  润新知