iOS小技巧總結

iOS小技巧總結###

參考iOS_小松哥的iOS小技巧總結

總結日常代碼生活中的小技巧,隨時可用

阿拉伯數(shù)字轉中文格式
阿拉伯數(shù)字轉中文格式
UITextField每四位加一個空格,實現(xiàn)代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // 四位加一個空格
    if ([string isEqualToString:@""])
    {
        // 刪除字符
        if ((textField.text.length - 2) % 5 == 0)
        {
            textField.text = [textField.text substringToIndex:textField.text.length - 1];
        }
        return YES;
    }
    else
    {
        if (textField.text.length % 5 == 0)
        {
            textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
        }
    }
    return YES;
}

禁止鎖屏

默認情況下嘲碱,當設備一段時間沒有觸控動作時,iOS會鎖住屏幕木蹬。但有一些應用是不需要鎖屏的蝇恶,比如視頻播放器。

[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

iOS 獲取漢字的拼音

+ (NSString *)transform:(NSString *)chinese
{    
    //將NSString裝換成NSMutableString 
    NSMutableString *pinyin = [chinese mutableCopy];    
    //將漢字轉換為拼音(帶音標)    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);    
    NSLog(@"%@", pinyin);    
    //去掉拼音的音標    
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);    
    NSLog(@"%@", pinyin);    
    //返回最近結果    
    return pinyin;
 }

手動更改iOS狀態(tài)欄的顏色

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
    {
        statusBar.backgroundColor = color;    
    }
}

NSArray 快速求總和 最大值 最小值 和 平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

修改UITextField中Placeholder的文字顏色

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
或
  textField.tintColor = [UIColor redColor];

關于NSDateFormatter的格式

G: 公元時代苗胀,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月狡刘,顯示為1-12
MMM: 月享潜,顯示為英文月份簡寫,如 Jan
MMMM: 月,顯示為英文月份全稱颓帝,如 Janualy
dd: 日米碰,2位數(shù)表示,如02
d: 日购城,1-2位顯示吕座,如 2
EEE: 簡寫星期幾,如Sun
EEEE: 全寫星期幾瘪板,如Sunday
aa: 上下午吴趴,AM/PM
H: 時,24小時制侮攀,0-23
K:時锣枝,12小時制,0-11
m: 分兰英,1-2位
mm: 分撇叁,2位
s: 秒,1-2位
ss: 秒畦贸,2位
S: 毫秒

UIImage 占用內存大小

UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);

圖片上繪制文字 寫一個UIImage的category

- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
{
    //畫布大小
    CGSize size=CGSizeMake(self.size.width,self.size.height);
    //創(chuàng)建一個基于位圖的上下文
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO  scale:0.0

    [self drawAtPoint:CGPointMake(0.0,0.0)];

    //文字居中顯示在畫布上
    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中

    //計算文字所占的size,文字居中顯示在畫布上
    CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;

    CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
    //繪制文字
    [title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];

    //返回繪制的新圖形
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

計算文件大小

//文件大小
- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:path])
    {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size;
    }

    return 0;
}

//文件夾大小
- (long long)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];

    long long folderSize = 0;

    if ([fileManager fileExistsAtPath:path])
    {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles)
        {
            NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
            if ([fileManager fileExistsAtPath:fileAbsolutePath])
            {
                long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
                folderSize += size;
            }
        }
    }

    return folderSize;
}

給UIView設置圖片

UIImage *image = [UIImage imageNamed:@"image"];
self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);

防止scrollView手勢覆蓋側滑手勢

[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];

獲取私有屬性和成員變量 #import <objc/runtime.h>

//獲取私有屬性 比如設置UIDatePicker的字體顏色
- (void)setTextColor
{
    //獲取所有的屬性陨闹,去查看有沒有對應的屬性
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
    for(int i = 0;i < count;i ++)
    {
        //獲得每一個屬性
        objc_property_t property = propertys[i];
        //獲得屬性對應的nsstring
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //輸出打印看對應的屬性
        NSLog(@"propertyname = %@",propertyName);
        if ([propertyName isEqualToString:@"textColor"])
        {
            [datePicker setValue:[UIColor whiteColor] forKey:propertyName];
        }
    }
}
//獲得成員變量 比如修改UIAlertAction的按鈕字體顏色
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
    for(int i =0;i < count;i ++)
    {
        Ivar ivar = ivars[i];
        NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
        NSLog(@"uialertion.ivarName = %@",ivarName);
        if ([ivarName isEqualToString:@"_titleTextColor"])
        {
            [alertOk setValue:[UIColor blueColor] forKey:@"titleTextColor"];
            [alertCancel setValue:[UIColor purpleColor] forKey:@"titleTextColor"];
        }
    }

獲取手機安裝的應用

Class c =NSClassFromString(@"LSApplicationWorkspace");
id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
for (id item in array)
{
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
    //NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
    NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
}

判斷兩個日期是否在同一周 寫在NSDate的category里面

- (BOOL)isSameDateWithDate:(NSDate *)date
{
    //日期間隔大于七天之間返回NO
    if (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
    {
        return NO;
    }

    NSCalendar *calender = [NSCalendar currentCalendar];
    calender.firstWeekday = 2;//設置每周第一天從周一開始
    //計算兩個日期分別為這年第幾周
    NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
    NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];

    //相等就在同一周跌造,不相等就不在同一周
    return countSelf == countDate;
}

應用內打開系統(tǒng)設置界面

//iOS8之后
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App沒有添加權限卷胯,顯示的是設定界面夺欲。如果App有添加權限(例如通知)府阀,顯示的是App的設定界面留潦。

獲取WebView所有的圖片地址

在網頁加載完成時燥撞,通過js獲取圖片和添加點擊的識別方式

//UIWebView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //這里是js酝惧,主要目的實現(xiàn)對url的獲取
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i<objs.length;i++){\
    imgScr = imgScr + objs[i].src + '+';\
    };\
    return imgScr;\
    };";

    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]];
    //urlResurlt 就是獲取到得所有圖片的url的拼接瞎饲;mUrlArray就是所有Url的數(shù)組
}
//WKWebView
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i<objs.length;i++){\
    imgScr = imgScr + objs[i].src + '+';\
    };\
    return imgScr;\
    };";

    [webView evaluateJavaScript:jsGetImages completionHandler:nil];
    [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@",result);
    }];
}

獲取到webview的高度

CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

navigationBar變?yōu)榧兺该?/em>

//第一種方法
//導航欄純透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉導航欄底部的黑線
self.navigationBar.shadowImage = [UIImage new];

//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;

navigationBar根據(jù)滑動距離的漸變色實現(xiàn)

//第一種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetToShow = 200.0;//滑動多少就完全顯示
    CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
    [[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
}
//第二種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetToShow = 200.0;
    CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;

    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}

//生成一張純色的圖片
- (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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return theImage;
}

iOS 開發(fā)中一些相關的路徑

模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 

文檔安裝位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

插件保存路徑:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins

自定義代碼段的保存路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets/ 
如果找不到CodeSnippets文件夾沈善,可以自己新建一個CodeSnippets文件夾乡数。

描述文件路徑
~/Library/MobileDevice/Provisioning Profiles

navigationItem的BarButtonItem如何緊靠屏幕右邊界或者左邊界?

一般情況下矮瘟,右邊的item會和屏幕右側保持一段距離:

image.png

下面是通過添加一個負值寬度的固定間距的item來解決瞳脓,也可以改變寬度實現(xiàn)不同的間隔:

UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//寬度為負數(shù)的固定間距的系統(tǒng)item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];

UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
image1.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市澈侠,隨后出現(xiàn)的幾起案子劫侧,更是在濱河造成了極大的恐慌,老刑警劉巖哨啃,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件烧栋,死亡現(xiàn)場離奇詭異,居然都是意外死亡拳球,警方通過查閱死者的電腦和手機审姓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來祝峻,“玉大人魔吐,你說我怎么就攤上這事扎筒。” “怎么了酬姆?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵嗜桌,是天一觀的道長。 經常有香客問我辞色,道長骨宠,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任相满,我火速辦了婚禮层亿,結果婚禮上,老公的妹妹穿的比我還像新娘立美。我一直安慰自己匿又,他們只是感情好,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布建蹄。 她就那樣靜靜地躺著琳省,像睡著了一般。 火紅的嫁衣襯著肌膚如雪躲撰。 梳的紋絲不亂的頭發(fā)上针贬,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機與錄音拢蛋,去河邊找鬼桦他。 笑死,一個胖子當著我的面吹牛谆棱,可吹牛的內容都是我干的快压。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼垃瞧,長吁一口氣:“原來是場噩夢啊……” “哼蔫劣!你這毒婦竟也來了?” 一聲冷哼從身側響起个从,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤脉幢,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后嗦锐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嫌松,經...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年奕污,在試婚紗的時候發(fā)現(xiàn)自己被綠了萎羔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡碳默,死狀恐怖贾陷,靈堂內的尸體忽然破棺而出缘眶,到底是詐尸還是另有隱情,我是刑警寧澤髓废,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布磅崭,位于F島的核電站,受9級特大地震影響瓦哎,放射性物質發(fā)生泄漏。R本人自食惡果不足惜柔逼,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一蒋譬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧愉适,春花似錦犯助、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至癌蓖,卻和暖如春瞬哼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背租副。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工坐慰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人用僧。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓结胀,卻偏偏與公主長得像,于是被迫代替她去往敵國和親责循。 傳聞我的和親對象是個殘疾皇子糟港,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內容

  • 在這里總結一些iOS開發(fā)中的小技巧,能大大方便我們的開發(fā) 原文地址:http://www.reibang.com/...
    Marray閱讀 333評論 0 0
  • 原文 在這里總結一些iOS開發(fā)中的小技巧院仿,能大大方便我們的開發(fā)秸抚,持續(xù)更新。 1.UITableView的Group...
    無灃閱讀 777評論 0 2
  • 在這里總結一些iOS開發(fā)中的小技巧歹垫,能大大方便我們的開發(fā)耸别,持續(xù)更新。 UITableView的Group樣式下頂部...
    UI愛好者閱讀 519評論 0 0
  • UITableView的Group樣式下頂部空白處理分組列表頭部空白處理UIView*view = [[UIVie...
  • 老公做生意歸來,剛踏進家門若贮。兒子拿著數(shù)學卷子屁爹爹的走到老公的身旁省有,笑瞇瞇的朝著老公說到:“爸爸痒留,這次的數(shù)學成績出...
    青竹風吟閱讀 489評論 0 3