項目中的小知識點(持續(xù)更新)

1.改變字符串中某幾個字的顏色
這是富文本,如下:

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

2.關于dataWithContentsOfURL請求經(jīng)常返回data時空,用下面這種方法可以基本解決問題,當然偶爾還有可能出現(xiàn)。。。
data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_lunboUrlArray[i]]] returningResponse:NULL error:nil];

3.用MJRefresh刷新返回崩潰,多半是沒有在dealloc方法里free,如果你free了,多半是你不止創(chuàng)建了一次tableview,你自己找找,看是不是在一個地方重復創(chuàng)建了tableview。

4.dictionaryWithObjectsAndKeys的坑
我們在初始化字典時候,經(jīng)常會用到dictionaryWithObjectsAndKeys,然而,這個方法有個坑,就是當元素中有個value是空的時候,后面的元素統(tǒng)一置為空了,而且還不會報錯~不會報錯??!。
解決方法:用setValue forkey ,注意value為字符串。
當然了setObject forkey也可以,但是為空時候會報錯(有提示的),需要判斷是否是空,所以還是用前者吧。

5.touchesBegan: withEvent: / touchesMoved: withEvent: / touchesEnded: withEvent: 等只能被UIView捕獲(如有問題請指出對請指出,路過的大牛請勿噴),當我們創(chuàng)建
UIScrollView 或 UIImageView 時,當點擊時UIScrollView 或 UIImageView 會截獲touch事件,導致touchesBegan: withEvent:/touchesMoved: withEvent:/touchesEnded: withEvent: 等方法執(zhí)行。解決辦法:當UIScrollView 或 UIImageView 截獲touch事件后,讓其傳遞下去即可(就是傳遞給其父視圖UIView)

可以通過寫UIScrollView 或 UIImageView 的category 重寫touchesBegan: withEvent: / touchesMoved: withEvent: / touchesEnded: withEvent: 等來實現(xiàn)
在.m中實現(xiàn)如下方法

- (void)touchesBegan:(NSSet<UITouch *> *)**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; 當前已經(jīng)下載的大小
        
        // 給Progress添加監(jiān)聽 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.獲取元素在數(shù)組中的位置

[myArray indexOfObject:num]

10.關于引用c文件時候的錯誤,最方法的做法是將.c文件修改為.m。具體參考http://www.itdecent.cn/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.只讓輸入字母和數(shù)字的鍵盤

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獲取設備上的信息,包括創(chuàng)建的唯一標識

這個作者寫的挺好的,我也試過了可以的,http://www.itdecent.cn/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
{
    //下面方法,第一個參數(shù)表示區(qū)域大小。第二個參數(shù)表示是否是非透明的。如果需要顯示半透明效果,需要傳NO,否則傳YES。第三個參數(shù)就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);

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

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

     return scaledImage;   //返回的就是已經(jīng)改變的圖片
 }

22.獲取當前時區(qū),北京時間

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 = @"如有疑問請聯(lián)系客服 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.數(shù)組倒敘

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",nil];  
//2.倒序的數(shù)組  
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];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容