iOS開發筆記

一、數組去重的最簡單方法:git

    NSArray *arr = @[@"aa",@"aa",@"bb"];
    arr = [arr valueForKeyPath:@"@distinctUnionOfObjects.self"];
    kDLOG(@"%@",arr);

    獲得的即爲去重後的數組,並且順序不變。github

      數組排序:web

   //按字母順序排序,其中keys爲要進行排序的字典
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {        return [obj1 compare:obj2 options:NSNumericSearch];
    }];

二、改變cell自帶imageView的大小算法

//cell自帶的imgeView是隻讀屬性,要改變大小須要重繪
    CGSize itemSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContext(itemSize);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    [cell.imageView.image drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

三、判斷屏幕局尺寸是否是5json

#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)

    一個宏即搞定。windows

四、將數組或者字典轉化成json數組

    有時候上傳數據的時候,要用到json來上傳,這個時候封裝一個方法,傳進去一個字典或者數據,出來就是一個json是否是很爽,so:cookie

#pragma mark - 將數組或字典轉化成json
+ (NSString*)objectToJson:(id )object{
    NSError *parseError = nil;
    //NSJSONWritingPrettyPrinted  是有換位符的。
    //若是NSJSONWritingPrettyPrinted 是nil 的話 返回的數據是沒有 換位符的
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&parseError];
    if (parseError) {
        kDLOG(@"轉化失敗:%@",parseError);
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

 

五、動態獲取字符串的range網絡

    通常狀況下獲取一個字符串中的某個特定的字符串的range採用app

NSRangeFromString(@"hello");

    這種形式便可,但大多數狀況下,咱們須要用的數據都是從後臺獲取的,這時再用這種方法就獲取不到了,需採用下面這種形式:

NSRange range2 = [integralString rangeOfString:[NSString stringWithFormat:@"%@",model.rule_score] options:NSBackwardsSearch];

    而獲取range最經常使用的地方就是使用富文本時對不一樣的字符串使用不一樣的字體顏色及大小,在粘貼一段項目中用到的富文本:

    //從後臺獲取的字符串,加上定製的「得到」
    NSString *integralString = [NSString stringWithFormat:@"%@得到%@",model.rule_action_desc,model.rule_score];
    //建立富文本
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:integralString];
    //設置字體大小
    [attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(0, attributedStr.string.length)];
    //分別得到想要改變字體顏色的range
    NSRange range1 = [integralString rangeOfString:[NSString stringWithFormat:@"%@得到",model.rule_action_desc] options:NSBackwardsSearch];
    NSRange range2 = [integralString rangeOfString:[NSString stringWithFormat:@"%@",model.rule_score] options:NSBackwardsSearch];
    //改變字體顏色
    [attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x333333) range:range1];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff4c79) range:range2];
    UILabel *integralScoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(timeLabel.frame.origin.x + timeLabel.frame.size.width + 30, timeLabel.frame.origin.y, 120, timeLabel.frame.size.height)];
    //設置label的attributedText
    integralScoreLabel.attributedText = attributedStr;

    其效果圖爲:

六、RGB顏色值轉化

    相信只要作app就必定會用到:

先來一個最方面最簡單的方法:
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

使用的時候直接:  view.backgroundColor = UIColorRGB(0x333333);
so easy!

或者:
#define rgb(r,g,b) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:1.0f]
#define rgba(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]

使用:
     self.backgroundColor = rgba(0, 0, 0, .5f);
固然這種方法也是能夠的,看着很長,用着也很簡單:

#pragma mark - RGB顏色值轉換
+(UIColor *) colorWithHexString: (NSString *) hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
    CGFloat alpha, red, blue, green;
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 1];
            green = [self colorComponentFrom: colorString start: 1 length: 1];
            blue  = [self colorComponentFrom: colorString start: 2 length: 1];
            break;
        case 4: // #ARGB
            alpha = [self colorComponentFrom: colorString start: 0 length: 1];
            red   = [self colorComponentFrom: colorString start: 1 length: 1];
            green = [self colorComponentFrom: colorString start: 2 length: 1];
            blue  = [self colorComponentFrom: colorString start: 3 length: 1];
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 2];
            green = [self colorComponentFrom: colorString start: 2 length: 2];
            blue  = [self colorComponentFrom: colorString start: 4 length: 2];
            break;
        case 8: // #AARRGGBB
            alpha = [self colorComponentFrom: colorString start: 0 length: 2];
            red   = [self colorComponentFrom: colorString start: 2 length: 2];
            green = [self colorComponentFrom: colorString start: 4 length: 2];
            blue  = [self colorComponentFrom: colorString start: 6 length: 2];
            break;
        default:
            [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
            break;
    }
    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}

七、根據時間戳返回一個時間字符串:

    封裝了一下幾種,能夠根據須要拿來使用,固然格式也是能夠本身修改的:

#pragma mark - 年月日字符串
+(NSString *)timeYMDStringFrom:(double )time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    //dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [dateFormatter setDateFormat:@"YYYY.MM.dd"];
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time/1000.0f];
    return  [dateFormatter stringFromDate:timeDate];
}
#pragma mark - 小時分字符串
+(NSString *)timeHMStringFrom:(double )time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    //dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time/1000.0f];
    return  [dateFormatter stringFromDate:timeDate];
}
#pragma mark - 月日字符串
+(NSString *)timeMDStingFrom:(double )time{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [dateFormatter setDateFormat:@"MM月dd日"];
    NSDate *timeDate = [NSDate dateWithTimeIntervalSince1970:time/1000.0f];
    return  [dateFormatter stringFromDate:timeDate];
}

八、根據顏色生成圖片

    這個就不用解釋了,直接上代碼:

#pragma mark - 根據顏色生成圖片
+ (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;
}

九、判斷字符串是否爲空

    這是我認爲相對來講比較全面的判斷字符串爲空的方法:

#pragma mark - 判斷字符串是否爲空
+(BOOL)isBlankString:(NSString *)string
{
    if (string == nil || string == NULL)
    {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0)
    {
        return YES;
    }
    return NO;
}

十、動態計算字符串的高度

    這個用處就比較大了,速度收藏:

#pragma mark - 動態計算字符串的高度
+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{
    if ([Tools getCurrentIOS] >= 7.0) {
        //iOS7以後
        /*
         第一個參數: 預設空間 寬度固定  高度預設 一個最大值
         第二個參數: 行間距 若是超出範圍是否截斷
         第三個參數: 屬性字典 能夠設置字體大小
         */
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
        CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        //返回計算出的行高
        return rect.size.height;
        
    }else {
        //iOS7以前
        /*
         1.第一個參數  設置的字體固定大小
         2.預設 寬度和高度 寬度是固定的 高度通常寫成最大值
         3.換行模式 字符換行
         */
        CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        return textSize.height;//返回 計算出得行高
    }
}

十一、獲取iOS版本號

+ (double)getCurrentIOS {
    return [[[UIDevice currentDevice] systemVersion] doubleValue];
}

十二、點擊空白收鍵盤,適用於全部能夠編輯的控件

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //關閉鍵盤的方法
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

1三、解決cell分割線不能從頭開始

    固然,不想這麼麻煩的話徹底能夠本身定製,這裏只是提供一個思路而已,把下面這兩個方法扔到tableView的界面,修改相應的tableView便可:

-(void)viewDidLayoutSubviews {
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

其中第一個方法是在controller裏面纔有效的,那若是不是在controller裏面寫這些方法的話,在建立tableView的時候能夠這樣來:

    tableView.separatorInset = UIEdgeInsetsZero;
    tableView.layoutMargins = UIEdgeInsetsZero;

 

 

1四、tableView的局部刷新

      咱們在用tableView時最習慣用的、也是寫起來最順手的就是[tableView reloadData] ,可是對於數據量比較大、複雜的tableView,這樣作事至關耗性能的,因此能用局部刷新的就用局部刷新,以提升性能:

//局部section刷新    
  NSIndexSet *set=[[NSIndexSet alloc]initWithIndex:1];//刷新第二個section
  [tableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
//局部cell刷新
  NSIndexPath *indexpath=[NSIndexPath indexPathForRow:2 inSection:0];//刷新第0個section的第3行
  [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationMiddle];

1五、設置圖片爲當前的背景

//設置圖片爲當前controller的背景色
    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"backImageplus"]];
//解決圖片不居中的問題
    self.view.layer.contents=(__bridge id _Nullable)[UIImage imageNamed:@"backImageplus"].CGImage;

1六、設置button上的字體左對齊

   button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;  
   button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

    其實只須要第一行代碼就能夠了,只是設置第一行後字體會牢牢貼着按鈕的邊界,不怎麼美觀,因此能夠設置edgeInsets.

1七、WKWebView添加cookie

    其實全部的要添加cookie的網絡請求包括web,最終都是要在request上添加,以下:

    web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, kScreen_width, kScreen_height - 64)];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSString *cookie = [Tools readCurrentCookie];
    [request addValue:cookie forHTTPHeaderField:@"Cookie"];
    [web loadRequest:request];

    其中得到cookie的信息我封裝了一下:

+(NSString *)readCurrentCookie{
    NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableString *cookieString = [[NSMutableString alloc] init];
    NSMutableString *domain = [[NSMutableString alloc] initWithString:kBaseUrl_New];
    NSArray *domainArr = [domain componentsSeparatedByString:@":"];
    NSMutableString *domainString = [NSMutableString stringWithString:domainArr[1]];
    [domainString deleteCharactersInRange:NSMakeRange(0, 2)];
    NSHTTPCookie *currentCookie= [[NSHTTPCookie alloc] init];
    for (NSHTTPCookie*cookie in [cookieJar cookies]) {
        kDLOG(@"cookie:%@", cookie);
        if ([cookie.domain isEqualToString:domainString]) {
            currentCookie = cookie;
            [cookieString appendFormat:@"%@=%@",cookie.name,cookie.value];
        }
        
    }
    return cookieString;
}

    在這裏,因爲app用到了兩個後臺,應用中保存了兩個cookie,因此我根據baseUrl來和domain來進行匹配,用以判斷哪個是咱們所須要的cookie,進而提取出咱們須要的信息,而提取的信息則根據後臺的須要去拼接,在本例中只用到了那麼和value,因此只提取出這些信息,添加到了web的cookie裏面,你們可根據須要進行相應的提取與拼接。

1八、成員變量、實例變量與基本數據類型變量

    以下圖:

    凡是在@interface 括號裏面的統稱爲「成員變量」,它包括實例變量和基本數據類型變量,也便是:

    成員變量 = 實例變量 + 基本數據類型變量。

    值得一提的是在類方法中,成員變量是不容許被使用的。

1九、數組排序

NSArray *stringArray = [NSArray arrayWithObjects:@"abc 1", @"abc 21", @"abc 12",@"abc 13",@"abc 05",nil];
   NSComparator sortBlock = ^(id string1, id string2){
            return [string1 compare:string2];
        };
   NSArray *sortArray = [stringArray sortedArrayUsingComparator:sortBlock];
   NSLog(@"sortArray:%@", sortArray);

  運行結果:

sortArray:(
  "abc 05",
  "abc 1",
  "abc 12",
  "abc 13",
  "abc 21"
)

20、小記一下block:    http://goshdarnblocksyntax.com/詳情請戳

How Do I Declare A Block in Objective-C?
As a local variable:

      returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};    
  
As a property:

      @property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);    
  
As a method parameter:

      - (void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes))blockName;    
  
As an argument to a method call:

      [someObject someMethodThatTakesABlock:^returnType (parameters) {...}];    
  
As a typedef:

      typedef returnType (^TypeName)(parameterTypes);

      TypeName blockName = ^returnType(parameters) {...};

PS:該圖片引自:http://blog.ibireme.com/2013/11/27/objc-block/

2一、gitignore須要添加的額忽略內容

.DS_Store
*/build/*
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
*.xcuserdatad
*.xcuserstate
xcuserdata
profile
*.moved-aside
DerivedData
.idea/
*.hmap

2二、mac下的一些小命令

<1>  應用進程窗口:command + option +esc

 <2> 不顯示系統的隱藏文件:defaults write com.apple.finder AppleShowAllFiles  NO(須要重啓finder)

         顯示系統的隱藏文件:   defaults write com.apple.finder AppleShowAllFiles  YES(須要重啓finder)

         重啓finder :(1)鼠標放到finder上,按住option,鼠標右鍵,會出現重啓finder字樣

                              (2)打開應用進程,找到finder,重啓

<3> 離保存網頁:command + s    ,用於保存一些網頁,以便於在無網絡的時候也能訪問。

2三、修改相機和相冊界面的文字爲中文

只須要將plist中的Localization native development region  的en修改爲China

2四、實用庫

將此庫導入到工程中便可實現收鍵盤的效果,不再用逐個頁面去寫了:

https://github.com/hackiftekhar/IQKeyboardManager

 

2五、經過消息響應者鏈找到UIView所在的UIViewController

- (UIViewController *) firstViewController {
    // convenience function for casting and to "mask" the recursive function
    return (UIViewController *)[self traverseResponderChainForUIViewController];
}
 
- (id) traverseResponderChainForUIViewController {
    id nextResponder = [self nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return nextResponder;
    } else if ([nextResponder isKindOfClass:[UIView class]]) {
        return [nextResponder traverseResponderChainForUIViewController];
    } else {
        return nil;
    }
}

2六、消除系統的deprecated警告

#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
   
   //寫系統會給咱們deprecated警告的代碼
   
#pragma clang diagnostic pop

2七、得到當前顯示界面的controller

//提供兩種方式
-(UIViewController *) getcurrentViewController{
#if 0
    UIWindow *window = [[UIApplication sharedApplication] windows].lastObject;
    UIView *frontView = [window subviews][0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return nextResponder;
    }else{
        return window.rootViewController;
    }
#else
    UIWindow *window = [[UIApplication sharedApplication] windows].lastObject;
    return ((UINavigationController *)window.rootViewController).visibleViewController;
    UIViewController * currVC = nil;
    UIViewController * Rootvc = window.rootViewController ;
    do {
        if ([Rootvc isKindOfClass:[UINavigationController class]]) {
            UINavigationController * nav = (UINavigationController *)Rootvc;
            UIViewController * v = [nav.viewControllers lastObject];
            currVC = v;
            Rootvc = v.presentedViewController;
            continue;
        }else if([Rootvc isKindOfClass:[UITabBarController class]]){
            UITabBarController * tabVC = (UITabBarController *)Rootvc;
            currVC = tabVC;
            Rootvc = [tabVC.viewControllers objectAtIndex:tabVC.selectedIndex];
            continue;
        }
        
    } while (Rootvc!=nil);
    return currVC;
#endif
}

2八、添加子controller

//添加子controller的正確方式
[self addChildViewController:newVC];
//[newVC willMoveToParentViewController:self];//這句代碼爲隱式調用
[self.view addSubview:newVC.view];
[newVC didMoveToParentViewController:self];

//移除子controller
[oldVC willMoveToParentViewController:nil];
[oldVC.view removeFromSuperview];
[oldVC removeFromParentViewController]; 
//[oldVC didMoveToParentViewController:nil];

文/KevinLee(簡書做者)
原文連接:http://www.jianshu.com/p/99f37dac2e8c
著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。

2九、判斷scrollview的滾動方向

-(BOOL )isScrolltoLeft:(UIScrollView *) scrollView{
    BOOL ret = NO;
    static CGFloat newX = 0;
    static CGFloat oldX = 0;
    newX = scrollView.contentOffset.x;
    if (newX > oldX) {
        ret = NO;
    }else{
        ret = YES;
    }
    oldX = newX;
    return ret;
}


#pragma mark - 判斷滾動方向
-(BOOL )isScrolltoLeft:(UIScrollView *) scrollView{
    //返回YES爲向左反動,NO爲右滾動
    if ([scrollView.panGestureRecognizer translationInView:scrollView.superview].x < 0) {
        return YES;
    }else{
        return NO;
    }
}

30、alpha與backgroundColor的alpha

    //這樣的話,將只改變view的透明度,而不會影響子控件的透明度
    view.backgroundColor = [self.backgroundColor colorWithAlphaComponent:0.5];
    //這樣設置,是view及其子控件都將出現透明效果
    view.alpha = 0.5;

3一、NS_ENUM 與 NS_OPTION

typedef NS_ENUM(NSInteger, LoginState) {
    LoginSuccess,
    loginFailed,
};
typedef NS_OPTIONS(NSInteger, Direction) {
    DirectionTop     =0,
    DirectionLeft    = 1 << 0,
    DirectionBottom  = 2 << 0,
    DirectionRight   = 3 << 0,
};

使用NS_OPTION可使用位運算,如:

 DirectionTop | DirectionBottom | DirectionLeft

 

3二、mac破解開機密碼:

一、長按 command + s 進入命令行
二、fsck -y
三、mount -uaw
四、rm/var/db/.AppleSetupDone
五、reboot

3三、網絡圖片測試用:

NSArray *networkImages=@[
                          @"http://www.netbian.com/d/file/20150519/f2897426d8747f2704f3d1e4c2e33fc2.jpg",
                          @"http://www.netbian.com/d/file/20130502/701d50ab1c8ca5b5a7515b0098b7c3f3.jpg",
                          @"http://www.netbian.com/d/file/20110418/48d30d13ae088fd80fde8b4f6f4e73f9.jpg",
                          @"http://www.netbian.com/d/file/20150318/869f76bbd095942d8ca03ad4ad45fc80.jpg",
                          @"http://www.netbian.com/d/file/20110424/b69ac12af595efc2473a93bc26c276b2.jpg",
                          @"http://www.netbian.com/d/file/20140522/3e939daa0343d438195b710902590ea0.jpg",
                          @"http://www.netbian.com/d/file/20141018/7ccbfeb9f47a729ffd6ac45115a647a3.jpg",
                          @"http://www.netbian.com/d/file/20140724/fefe4f48b5563da35ff3e5b6aa091af4.jpg",
                          @"http://www.netbian.com/d/file/20140529/95e170155a843061397b4bbcb1cefc50.jpg"
                          ];

 

3四、MD5加密:

- (NSString *)MD5Hash
{
	const char *cStr = [self UTF8String];
	unsigned char result[16];
	CC_MD5(cStr, strlen(cStr), result);
	return [NSString stringWithFormat:
			@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
			result[0], result[1], result[2], result[3], 
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15]];
}

 

3五、iOS對小數四捨五入:

CGFloat num = 5.567;
    NSLog(@"%.2f",num);
//其實當咱們直接去保留幾位小數的時候,系統已經幫咱們自動去處理了(四捨五入),看到網上有部分童靴弄了一堆算法來計算這個四捨五入,徹底是沒不要的,不是嗎?

3六、scrollView放大圖片:

-(void)createScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _scrollView.minimumZoomScale = 0.1;
    _scrollView.maximumZoomScale = 5;
    _scrollView.pagingEnabled = YES;
    //添加圖片控件
    UIImage *image=[UIImage imageNamed:@"myIcon.jpg"];
    _imageView=[[UIImageView alloc]initWithImage:image];
    _imageView.frame = CGRectMake(0, 0, _imageView.image.size.width, _imageView.image.size.height);
    [_scrollView addSubview:_imageView];
    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    
}
//此方法必須實現,不然scrollview將不相應放大的手勢操做
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return _imageView;//返回scrollview的imageView
}
#pragma mark 當圖片小於屏幕寬高時縮放後讓圖片顯示到屏幕中間
-(void)scrollViewDidZoom:(UIScrollView *)scrollView{
    CGSize originalSize=_scrollView.bounds.size;
    CGSize contentSize=_scrollView.contentSize;
    CGFloat offsetX=originalSize.width>contentSize.width?(originalSize.width-contentSize.width)/2:0;
    CGFloat offsetY=originalSize.height>contentSize.height?(originalSize.height-contentSize.height)/2:0;
    
    _imageView.center=CGPointMake(contentSize.width/2+offsetX, contentSize.height/2+offsetY);
}

3七、夜間模式:

//最好用的第三方:
DKNightVersion

使用方法:
一、#import <DKNightVersion/DKNightVersion.h>
二、self.view.dk_backgroundColorPicker = DKColorPickerWithKey(BG);
三、在須要改變主題模式的地方調用:
    DKNightVersionManager *manager = [DKNightVersionManager sharedManager];
    manager.themeVersion = DKThemeVersionNight;

3八、快捷鍵

 

option + command +   [  或  ]   將選中的代碼向上或者向下移動

 

3九、調試:

 

thread info 命令能夠查看當前斷點線程的信息,若是再加上一個數字參數表示查看某個線程號的信息

thread backtrace 能夠查看調用棧。
相關文章
相關標籤/搜索