iOS小點(diǎn)整理

1、設(shè)置navigationBar title的顏色

UIColor *whiteColor = [UIColor whiteColor];
NSDictionary *dic = [NSDictionary dictionaryWithObject:whiteColor forKey:NSForegroundColorAttributeName];
[self.navigationController.navigationBar setTitleTextAttributes:dic];

2、修改textField的placeholder的字體顏色、大小

a.通過kvo設(shè)置
self.textField.placeholder = @"請(qǐng)輸入商品名稱";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
b.通過富文本設(shè)置
NSString *string = @"請(qǐng)輸入商品名稱";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];

[attributedString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:NSMakeRange(0, [string length])];
 
[attributedString addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:16]
                             range:NSMakeRange(0, [string length])];
 
self.textField.attributedPlaceholder = attributedString;

3、關(guān)閉/收起鍵盤方法

a.點(diǎn)擊Return按扭時(shí)收起鍵盤
-(BOOL)textFieldShouldReturn:(UITextField*)textField{
    return [textField resignFirstResponder]; 
}
b.點(diǎn)擊背景View收起鍵盤
[self.view endEditing:YES];
c.在任何地方統(tǒng)一收起鍵盤
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

4、將color轉(zhuǎn)為UIImage

-(UIImage*)createImageWithColor:(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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

5、NSString進(jìn)行URL編碼轉(zhuǎn)換

urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

6、清理內(nèi)存

// 清理內(nèi)存
[[SDImageCache sharedImageCache] clearMemory];
 
// 清理webview 緩存
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}
 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config.URLCache removeAllCachedResponses];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
 
// 清理硬盤
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
 
    [self.tableView reloadData];
}];

7、返回一個(gè)沒有重復(fù)元素的數(shù)組

-(NSArray *)arrayWithMemberIsOnly:(NSArray *)array{
    NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < [array count]; i++) {
       if ([categoryArray containsObject:[array objectAtIndex: i]] == NO) {
           [categoryArray addObject:[array objectAtIndex: i]];
       }
    }
   return categoryArray;
}

8、限制UITextField字?jǐn)?shù)

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.text.length + string.length > 18) {
        return NO;
    }
    if (textField.text.length < range.location + range.length) {
        return NO;
    }
    return YES;
}

9、隱私數(shù)據(jù)訪問問題
項(xiàng)目中訪問了隱私數(shù)據(jù),比如:相機(jī),相冊(cè),聯(lián)系人等,在Xcode8中打開編譯的話,統(tǒng)統(tǒng)會(huì)crash.提交App Store會(huì)被拒絕,可以才info.plist中添加如下設(shè)置:

<!-- 相冊(cè) --> 
<key>NSPhotoLibraryUsageDescription</key> 
<string>App需要您的同意,才能訪問相冊(cè)</string> 
<!-- 相機(jī) --> 
<key>NSCameraUsageDescription</key> 
<string>App需要您的同意,才能訪問相機(jī)</string> 
<!-- 麥克風(fēng) --> 
<key>NSMicrophoneUsageDescription</key> 
<string>App需要您的同意,才能訪問麥克風(fēng)</string> 
<!-- 位置 --> 
<key>NSLocationUsageDescription</key> 
<string>App需要您的同意,才能訪問位置</string> 
<!-- 在使用期間訪問位置 --> 
<key>NSLocationWhenInUseUsageDescription</key> 
<string>App需要您的同意,才能在使用期間訪問位置</string> 
<!-- 始終訪問位置 --> 
<key>NSLocationAlwaysUsageDescription</key> 
<string>App需要您的同意,才能始終訪問位置</string> 
<!-- 日歷 --> 
<key>NSCalendarsUsageDescription</key> 
<string>App需要您的同意,才能訪問日歷</string> 
<!-- 提醒事項(xiàng) --> 
<key>NSRemindersUsageDescription</key> 
<string>App需要您的同意,才能訪問提醒事項(xiàng)</string> 
<!-- 運(yùn)動(dòng)與健身 --> 
<key>NSMotionUsageDescription</key> <string>App需要您的同意,才能訪問運(yùn)動(dòng)與健身</string> 
<!-- 健康更新 --> 
<key>NSHealthUpdateUsageDescription</key> 
<string>App需要您的同意,才能訪問健康更新 </string> 
<!-- 健康分享 --> 
<key>NSHealthShareUsageDescription</key> 
<string>App需要您的同意,才能訪問健康分享</string> 
<!-- 藍(lán)牙 --> 
<key>NSBluetoothPeripheralUsageDescription</key> 
<string>App需要您的同意,才能訪問藍(lán)牙</string> 
<!-- 媒體資料庫(kù) --> 
<key>NSAppleMusicUsageDescription</key> 
<string>App需要您的同意,才能訪問媒體資料庫(kù)</string>

10、銀行卡校驗(yàn)碼算法

-(void)getBankCardCheckCode{

    NSString *cardNumber = @"625965087177209";
    NSMutableString *checkCode = [NSMutableString string];
    //校驗(yàn)碼為銀行卡號(hào)最后一位,采用LUHN算法,亦稱模10算法。計(jì)算方法如下:
   
    for (NSInteger i = 0; i < cardNumber.length; i+=2) {
        //第一步:從右邊第1個(gè)數(shù)字開始每隔一位乘以2;
        NSString *str = [cardNumber substringWithRange:NSMakeRange(i, 1)];
        [checkCode appendString:[NSString stringWithFormat:@"%ld", [str integerValue] * 2]];
    }
   
    NSInteger sum = 0;
    for (NSInteger i = 0; i < checkCode.length; i++) {
        //第二步: a.把在第一步中獲得的乘積的各位數(shù)字相加,然
        NSInteger number = [[checkCode substringWithRange:NSMakeRange(i, 1)] integerValue];
        sum += number;
       
    }
   
    for (NSInteger i = 1; i < cardNumber.length; i+=2) {
        //b.后再與原號(hào)碼中未乘2的各位數(shù)字相加;
        NSInteger number = [[cardNumber substringWithRange:NSMakeRange(i, 1)] integerValue];
        sum += number;
    }
   
    //第三步:對(duì)于第二步求和值中個(gè)位數(shù)求10的補(bǔ)數(shù),如果個(gè)位數(shù)為0則該校驗(yàn)碼為0。
    NSInteger code = 10 - (sum%10);
    NSString *fullCardNumber = [NSString stringWithFormat:@"%@%ld", cardNumber, code];
   
    NSLog(@"fullCardNumber:%@", fullCardNumber);
}

11、設(shè)置label文字屬性,一半斜體一半sys,一半紅色,一半黑色

    _starGoodsLabel = [[UILabel alloc] init];
    CGAffineTransform matrix =  CGAffineTransformMake(1, 0, tanf(15 * (CGFloat)M_PI / 180), 1, 0, 0);
    UIFontDescriptor *desc = [ UIFontDescriptor fontDescriptorWithName :[ UIFont systemFontOfSize :17 ]. fontName matrix :matrix];
    _starGoodsLabel.font = [ UIFont fontWithDescriptor :desc size :17];
    _starGoodsLabel.textColor = [UIColor redColor];
    NSString *string = @"/ 底價(jià)秒殺 /  人人都在搶的貨";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string];
    [str addAttribute:NSForegroundColorAttributeName value:RGB(68, 68, 68) range:NSMakeRange(10, string.length - 10)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(10, string.length - 10)];
    _starGoodsLabel.attributedText = str;
    [view addSubview:_starGoodsLabel];
    [_starGoodsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(10);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-120);
        make.top.mas_equalTo(self.contentView.mas_top).offset(7);
        make.height.equalTo(@14);
    }];

12、截圖

//截取view生成一張圖片
+ (UIImage *)shotWithView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//截取view中某個(gè)區(qū)域生成一張圖片
+ (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
    UIGraphicsBeginImageContext(scope.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
    CGContextTranslateCTM(context, 0, rect.size.height);//下移
    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
    CGContextDrawImage(context, rect, imageRef);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(imageRef);
    CGContextRelease(context);
    return image;
}

13、日期與時(shí)間戳互轉(zhuǎn)

//將時(shí)間戳轉(zhuǎn)換為NSDate類型
-(NSDate*)getDateTimeFromMilliSeconds:(long long)miliSeconds{
    
    NSTimeInterval tempMilli = miliSeconds;
    NSTimeInterval seconds = tempMilli/1000.0;//這里的.0一定要加上,不然除下來的數(shù)據(jù)會(huì)被截?cái)鄬?dǎo)致時(shí)間不一致
    NSLog(@"傳入的時(shí)間戳=%f", seconds);
    return [NSDate dateWithTimeIntervalSince1970: seconds];
}

//將NSDate類型的時(shí)間轉(zhuǎn)換為時(shí)間戳,從1970/1/1開始
-(long long)getDateTimeTOMilliSeconds:(NSDate*)datetime{
    
    NSTimeInterval interval = [datetime timeIntervalSince1970];
    NSLog(@"轉(zhuǎn)換的時(shí)間戳=%f", interval);
    long long totalMilliseconds = interval*1000;
    NSLog(@"totalMilliseconds=%llu", totalMilliseconds);
    return totalMilliseconds;
}

14、指紋識(shí)別返回碼

a、 驗(yàn)證(指紋/密碼)不能開啟的錯(cuò)誤信息(指紋系統(tǒng)被判定為無(wú)效):
LAErrorPasscodeNotSet : 設(shè)備密碼未設(shè)置
LAErrorTouchIDNotAvailable : TOUCH ID不可用
LAErrorTouchIDNotEnrolled : 指紋未錄入
LAErrorTouchIDLockout : TOUCH ID被鎖定
LAErrorAppCancel : APP調(diào)用了- (void)invalidate方法使LAContext失效
LAErrorInvalidContext : 實(shí)例化的LAContext對(duì)象失效,再次調(diào)用evaluation...方法則會(huì)彈出此錯(cuò)誤信息
b、 其他錯(cuò)誤信息(指紋系統(tǒng)判定有效,但是驗(yàn)證指紋錯(cuò)誤):
LAErrorAuthenticationFailed : 鑒定失敗
LAErrorUserCancel : 用戶取消
LAErrorUserFallback : 用戶選擇輸入密碼
LAErrorSystemCancel : 系統(tǒng)取消(如:另外一個(gè)應(yīng)用進(jìn)入前臺(tái))

15、解決tableView分隔線少一段的方法
在ios7中,UITableViewCell左側(cè)會(huì)有默認(rèn)15像素的空白。這時(shí)候,設(shè)置setSeparatorInset:UIEdgeInsetsZero能將空白去掉。
但是在ios8中,設(shè)置setSeparatorInset:UIEdgeInsetsZero已經(jīng)不起作用了。下面是解決辦法

首先在viewDidLoad方法加入以下代碼:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
然后在UITableView的代理方法中加入以下代碼
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容