项目中的小知识点(持续更新)

1.改变字符串中某几个字的颜色
这是富文本,如下:

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"123456789"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,1)];
label.attributedText = str; 

2.关于dataWithContentsOfURL请求经常返回data时空,用下面这种方法可以基本解决问题,当然偶尔还有可能出现。。。
data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_lunboUrlArray[i]]] returningResponse:NULL error:nil];

3.用MJRefresh刷新返回崩溃,多半是没有在dealloc方法里free,如果你free了,多半是你不止创建了一次tableview,你自己找找,看是不是在一个地方重复创建了tableview。

4.dictionaryWithObjectsAndKeys的坑
我们在初始化字典时候,经常会用到dictionaryWithObjectsAndKeys,然而,这个方法有个坑,就是当元素中有个value是空的时候,后面的元素统一置为空了,而且还不会报错~不会报错!!
解决方法:用setValue forkey ,注意value为字符串。
当然了setObject forkey也可以,但是为空时候会报错(有提示的),需要判断是否是空,所以还是用前者吧。

5.touchesBegan: withEvent: / touchesMoved: withEvent: / touchesEnded: withEvent: 等只能被UIView捕获(如有问题请指出对请指出,路过的大牛请勿喷),当我们创建
UIScrollView 或 UIImageView 时,当点击时UIScrollView 或 UIImageView 会截获touch事件,导致touchesBegan: withEvent:/touchesMoved: withEvent:/touchesEnded: withEvent: 等方法执行。解决办法:当UIScrollView 或 UIImageView 截获touch事件后,让其传递下去即可(就是传递给其父视图UIView)

可以通过写UIScrollView 或 UIImageView 的category 重写touchesBegan: withEvent: / touchesMoved: withEvent: / touchesEnded: withEvent: 等来实现
在.m中实现如下方法

- (void)touchesBegan:(NSSet *)**touches** withEvent:(UIEvent *)event{ // 选其一即可 [super touchesBegan:**touches** withEvent:event];// [[self nextResponder] touchesBegan:**touches** withEvent:event];}

6.引用第三方文件的时候,如果有.mm文件的,一定要注意,在other linker flags 里面写-ObjC(被坑惨了)

7.iOS中当有导航栏的情况下,tableView设置起始点为0,0,是会自动默认在导航栏下面开始,如果不要这种默认效果,我们只需要在viewdidload中self.automaticallyAdjustsScrollViewInsets = NO;即可。具体的原因应该是tableView有headview时候会默认的。这个问题我在解决MJRefresh下拉刷新时候碰到的bug,这样可以修复导致弹不上去。

8.iOS中文件下载
AF3.0 中 NSURLSessionDownloadTask,

NSURLSessionDownloadTask *_downloadTask;
NSURL *URL = [NSURL URLWithString:@"http://pic6.nipic.com/20100330/4592428_113348097000_2.jpg"];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    //AFN3.0+基于封住URLSession的句柄
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //下载Task操作
    _downloadTask = [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(), ^{
            self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            _titlelabel.text = [NSString stringWithFormat:@"当前进度为:%.2f%%",(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount) * 100];
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径
        
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        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
//        UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];
        NSLog(@"img == %@", imgFilePath);
        if (imgFilePath) {
            [self cancelDownload];
            _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT - 44 - 64)];
            [_webView setUserInteractionEnabled:YES];//是否支持交互
            //[webView setDelegate:self];
            _webView.delegate=self;
            [_webView setOpaque:NO];//opaque是不透明的意思
            [_webView setScalesPageToFit:YES];//自动缩放以适应屏幕
            [self.view addSubview:_webView];
            NSURL *url = [NSURL fileURLWithPath:imgFilePath];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            [_webView loadRequest:request];
        }
    }];
    [_downloadTask resume];

取消下载

[_downloadTask cancel];
    _downloadTask = nil;

9.获取元素在数组中的位置

[myArray indexOfObject:num]

10.关于引用c文件时候的错误,最方法的做法是将.c文件修改为.m。具体参考http://www.jianshu.com/p/66eeefdbc246

11.利用正则表达式来解决字符串替换一个范围内的内容

    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"[0-9A-Z]."
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];
    NSString *aaa = [regExp stringByReplacingMatchesInString:model.accountNum
                                                 options:NSMatchingReportProgress
                                                   range:NSMakeRange(0, model.accountNum.length - 3)
                                            withTemplate:@"**"];

12.字符串前空格

if (_nameTF.text.trim.length == 0) {
        [Tool HUDShowAddedTo:self.view withTitle:@"收件人姓名开头不能输入空格" delay:1.5];
        return;
    }

13.只让输入字母和数字的键盘

UIKeyboardTypeASCIICapable

14.textfield中禁止输出空格

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _pinpaiTF) {
        NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
        if (![string isEqualToString:tem]) {
            return NO;
        }
    }
    return YES;
}

15.设置uitextfield为圆角不透明

textFiled1.borderStyle=UITextBorderStyleRoundedRect

16.判断是否是真机还是模拟器

TARGET_IPHONE_SIMULATOR
TARGET_OS_IPHONE

17.获取设备名字

[[UIDevice currentDevice] name];

18获取设备上的信息,包括创建的唯一标识

这个作者写的挺好的,我也试过了可以的,http://www.jianshu.com/p/a7018a6d107b

19.NSData转字符串,为空,是因为encoding不对,里面的内容应该不是汉字,用如下方法

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000); 
NSString *rawString=[[NSString alloc]initWithData:inData encoding:enc]; 

20.二维码扫描

下面的链接是github地址,写的挺好的,原生的,view的背景可换成黑色,就不会白色一闪了。
[https://github.com/liutongchao/LCQRCodeUtil]

21.图片的裁剪

- (UIImage*)imageWithImage:(UIImage*)image scaledToSize: (CGSize)newSize
{
    //下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

     return scaledImage;   //返回的就是已经改变的图片
 }

22.获取当前时区,北京时间

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    [formatter setDateFormat : @"yyyy.MM.dd"];
    NSDate *dateTimeOne = [formatter dateFromString:_timeStringOne];

23.强行禁止侧滑(说多了都是泪)

id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
[self.view addGestureRecognizer:pan];

直接将代码拷贝到viewDidLoad总就行了

24 将label中的某段话的颜色改变

 telLabel.text = @"如有疑问请联系客服 12345677";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:telLabel.text];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,9)];
    telLabel.attributedText = str;

25.修改button中部分字体颜色

NSString*str =@"已有账号,去登录";
    NSMutableAttributedString* attributedString1 = [[NSMutableAttributedString alloc]initWithString:str];
    [attributedString1 addAttribute:NSForegroundColorAttributeName value:BSColor(25, 130, 210, 1.0)range:NSMakeRange(0,5)];
    [registerBtn setAttributedTitle:attributedString1 forState:UIControlStateNormal];
    [registerBtn sizeToFit];

26 Xcode没有提示

1.找到 这个 DerivedData 文件夹 删除 (路径: ~/Library/Developer/Xcode/DerivedData)
2.删除这个 com.apple.dt.Xcode 文件 (路径: ~/Library/Caches/com.apple.dt.Xcode)
3.重启xcode即可

27.xcode中pch的相对路径的设置

有时候我们本地复制一个工程,作为版本记录,他的pch还是指向原来工程的路径,这个时候,我们修改一下pch的路径,$(SRCROOT)/工程名称/文件夹/pch

28.textfield的代理方法

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

获取textfield的值

NSMutableString *textString = [textField.text mutableCopy];
  [textString replaceCharactersInRange:range withString:string];

29.tableView加了个footerview,滑不到底部的问题

_tableView.contentInset = UIEdgeInsetsMake(0, 0, 67, 0);

设置一下上面的代码即可

30.数组倒叙

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",nil];  
//2.倒序的数组  
NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];  

31 启动页封装比较好的

github地址:https://github.com/CoderZhuXH/XHLaunchAd

32.自定义相机功能,底层的一些东西,看下面两个文章

https://www.2cto.com/kf/201409/335951.html 还有 https://www.cnblogs.com/carlos-mm/p/6524604.html,前者是摄像头反转的问题,后者是相机上加自定义的框,裁剪。

33.禁止侧滑

id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];

你可能感兴趣的:(项目中的小知识点(持续更新))