iOS技巧

原文連接http://www.reibang.com/p/4523eafb4cd4
UITableView的Group樣式下頂部空白處理

//分組列表頭部空白處理
 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;
UITableView的plain樣式下,取消區(qū)頭停滯效果
 - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat sectionHeaderHeight = sectionHead.height;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView;.contentOffset.y>=0)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }
        else if(scrollView.contentOffset.y>=sectionHeaderHeight)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }

獲取某個view所在的控制器

- (UIViewController *)viewController
{
    UIViewController *viewController = nil;
    UIResponder *next = self.nextResponder;
    while (next)
    {
        if ([next isKindOfClass:[UIViewController class]])
        {
            viewController = (UIViewController *)next;
            break;
        }
        next = next.nextResponder;
    } 
    return viewController;
}

兩種方法刪除NSUserDefaults所有記錄

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];`
//方法二

- (void)resetDefaults
{
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict)
    {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];
}

獲取圖片某一點(diǎn)的顏色

- (UIColor*) getPixelColorAtLocation:(CGPoint)point inImage:(UIImage *)image
{
    
    UIColor* color = nil;
    CGImageRef inImage = image.CGImage;
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    
    if (cgctx == NULL) {
        return nil; /* error */
    }
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}};
    
    CGContextDrawImage(cgctx, rect, inImage);
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        int offset = 4*((w*round(point.y))+round(point.x));
        int alpha =  data[offset];
        int red = data[offset+1];
        int green = data[offset+2];
        int blue = data[offset+3];
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:
                 (blue/255.0f) alpha:(alpha/255.0f)];
    }
    CGContextRelease(cgctx);
    if (data) {
        free(data);
    }
    return color;
}

字符串反轉(zhuǎn)

第一種:
  - (NSString *)reverseWordsInString:(NSString *)str
{
    NSMutableString *newString = [[NSMutableString alloc] initWithCapacity:str.length];
    for (NSInteger i = str.length - 1; i >= 0 ; i --)
    {
        unichar ch = [str characterAtIndex:i];
        [newString appendFormat:@"%c", ch];
    }
    return newString;
}
//第二種:
- (NSString*)reverseWordsInString:(NSString*)str
{
    NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];
    [str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [reverString appendString:substring];
    }];
    return reverString;
}

禁止鎖屏

默認(rèn)情況下剑肯,當(dāng)設(shè)備一段時間沒有觸控動作時退唠,iOS會鎖住屏幕俺泣。但有一些應(yīng)用是不需要鎖屏的,比如視頻播放器
[UIApplication sharedApplication].idleTimerDisabled = YES;
或[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
模態(tài)推出透明界面
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){ 
    na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}else{ 
    self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];

Xcode調(diào)試不顯示內(nèi)存占用

editSCheme 里面有個選項(xiàng)叫叫做enable zoombie Objects 取消選中

顯示隱藏文件

//顯示
defaults write com.apple.finder AppleShowAllFiles -bool truekillall Finder
//隱藏
defaults write com.apple.finder AppleShowAllFiles -bool falsekillall Finder

iOS跳轉(zhuǎn)到App Store下載應(yīng)用評分

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];

iOS 獲取漢字的拼音

+ (NSString *)transform:(NSString *)chinese{ 
//將NSString裝換成NSMutableString  
NSMutableString *pinyin = [chinese mutableCopy];
 //將漢字轉(zhuǎn)換為拼音(帶音標(biāo))  
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); NSLog(@"%@", pinyin); //去掉拼音的音標(biāo)  CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); NSLog(@"%@", pinyin); 
//返回最近結(jié)果  
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; 
}
}

判斷當(dāng)前ViewController是push還是present的方式顯示的

NSArray *viewcontrollers=self.navigationController.viewControllers;

if (viewcontrollers.count > 1)
{
    if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
    {
        //push方式
        [self.navigationController popViewControllerAnimated:YES];
    }
}
else
{
    //present方式
    [self dismissViewControllerAnimated:YES completion:nil];
}

獲取實(shí)際使用的LaunchImage圖片

- (NSString *)getLaunchImageName
{
    CGSize viewSize = self.window.bounds.size;
    // 豎屏
    NSString *viewOrientation = @"Portrait";
    NSString *launchImageName = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict)
    {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];
        }
    }
    return launchImageName;
}

iOS在當(dāng)前屏幕獲取第一響應(yīng)

UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];

判斷對象是否遵循了某協(xié)議

    if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
    {
        [self.selectedController performSelector:@selector(onTriggerRefresh)];
    }

判斷view是不是指定視圖的子視圖

BOOL isView = [textView isDescendantOfView:self.view];

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"];

關(guān)于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: 毫秒

獲取一個類的所有子類

+ (NSArray *) allSubclasses
{
    Class myClass = [self class];
    NSMutableArray *mySubclasses = [NSMutableArray array];
    unsigned int numOfClasses;
    Class *classes = objc_copyClassList(&numOfClasses;);
    for (unsigned int ci = 0; ci < numOfClasses; ci++)
    {
        Class superClass = classes[ci];
        do{
            superClass = class_getSuperclass(superClass);
        } while (superClass && superClass != myClass);
        
        if (superClass)
        {
            [mySubclasses addObject: classes[ci]];
        }
    }
    free(classes);
    return mySubclasses;
}

監(jiān)測IOS設(shè)備是否設(shè)置了代理淫僻,需要CFNetwork.framework

NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);

NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);

if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
    NSLog(@"沒代理");
}
else
{
    NSLog(@"設(shè)置了代理");
}

阿拉伯?dāng)?shù)字轉(zhuǎn)中文格式

+(NSString *)translation:(NSString *)arebic
{
    NSString *str = arebic;
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
    
    NSMutableArray *sums = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
        NSString *a = [dictionary objectForKey:substr];
        NSString *b = digits[str.length -i-1];
        NSString *sum = [a stringByAppendingString:b];
        if ([a isEqualToString:chinese_numerals[9]])
        {
            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
            {
                sum = b;
                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
                {
                    [sums removeLastObject];
                }
            }else
            {
                sum = chinese_numerals[9];
            }
            
            if ([[sums lastObject] isEqualToString:sum])
            {
                continue;
            }
        }
        
        [sums addObject:sum];
    }
    
    NSString *sumStr = [sums componentsJoinedByString:@""];
    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
    NSLog(@"%@",str);
    NSLog(@"%@",chinese);
    return chinese;
}

Base64編碼與NSString對象或NSData對象的轉(zhuǎn)換

// Create NSData object
NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
                  dataUsingEncoding:NSUTF8StringEncoding];

// Get NSString from NSData object in Base64
NSString *base64Encoded = [nsdata base64EncodedStringWithOptions:0];

// Print the Base64 encoded string
NSLog(@"Encoded: %@", base64Encoded);

// Let's go the other way...

// NSData from the Base64 encoded str
NSData *nsdataFromBase64String = [[NSData alloc]
                                  initWithBase64EncodedString:base64Encoded options:0];

// Decoded NSString from the NSData
NSString *base64Decoded = [[NSString alloc]
                           initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
NSLog(@"Decoded: %@", base64Decoded);

取消UICollectionView的隱式動畫
UICollectionView在reloadItems的時候诱篷,默認(rèn)會附加一個隱式的fade動畫,有時候很討厭雳灵,尤其是當(dāng)你的cell是復(fù)合cell的情況下(比如cell使用到了UIStackView)棕所。
下面幾種方法都可以幫你去除這些動畫

 //方法一
    [UIView performWithoutAnimation:^{
        [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    }];
    
    //方法二
    [UIView animateWithDuration:0 animations:^{
        [collectionView performBatchUpdates:^{
            [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
        } completion:nil];
    }];
    
    //方法三
    [UIView setAnimationsEnabled:NO];
    [self.trackPanel performBatchUpdates:^{
        [collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    } completion:^(BOOL finished) {
        [UIView setAnimationsEnabled:YES];
    }];

讓Xcode的控制臺支持LLDB類型的打印

打開終端輸入三條命令:
    touch ~/.lldbinit
    echo display @import UIKit >> ~/.lldbinit
    echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

CocoaPods pod install/pod update更新慢的問題

    pod install --verbose --no-repo-update
    pod update --verbose --no-repo-update
    如果不加后面的參數(shù),默認(rèn)會升級CocoaPods的spec倉庫悯辙,加一個參數(shù)可以省略這一步琳省,然后速度就會提升不少

UIImage 占用內(nèi)存大小

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

GCD timer定時器

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執(zhí)行
    dispatch_source_set_event_handler(timer, ^{
        //@"倒計(jì)時結(jié)束,關(guān)閉"
        dispatch_source_cancel(timer);
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
    dispatch_resume(timer);

圖片上繪制文字 寫一個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;//文字居中
    
    //計(jì)算文字所占的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;
}

查找一個視圖的所有子視圖

- (NSMutableArray *)allSubViewsForView:(UIView *)view
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    for (UIView *subView in view.subviews)
    {
        [array addObject:subView];
        if (subView.subviews.count > 0)
        {
            [array addObjectsFromArray:[self allSubViewsForView:subView]];
        }
    }
    return array;
}

計(jì)算文件大小

//文件大小
- (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設(shè)置部分圓角
你是不是也遇到過這樣的問題躲撰,一個button或者label针贬,只要右邊的兩個角圓角,或者只要一個圓角拢蛋。該怎么辦呢桦他。這就需要圖層蒙版來幫助我們了

    CGRect rect = view.bounds;
    CGSize radio = CGSizeMake(30, 30);//圓角尺寸
    UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//這只圓角位置
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
    CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//創(chuàng)建shapelayer
    masklayer.frame = view.bounds;
    masklayer.path = path.CGPath;//設(shè)置路徑
    view.layer.mask = masklayer;

取上整與取下整

   floor(x),有時候也寫做Floor(x),其功能是“下取整”谆棱,即取不大于x的最大整數(shù) 例如:
    x=3.14快压,floor(x)=3
    y=9.99999,floor(y)=9
    
    與floor函數(shù)對應(yīng)的是ceil函數(shù)础锐,即上取整函數(shù)嗓节。
    
    ceil函數(shù)的作用是求不小于給定實(shí)數(shù)的最小整數(shù)。
    ceil(2)=ceil(1.2)=cei(1.5)=2.00
    
    floor函數(shù)與ceil函數(shù)的返回值均為double型

計(jì)算字符串字符長度皆警,一個漢字算兩個字符

//方法一:
- (int)convertToInt:(NSString*)strtemp
{
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++)
    {
        if (*p)
        {
            p++;
            strlength++;
        }
        else
        {
            p++;
        }
        
    }
    return strlength;
}

//方法二:
-(NSUInteger) unicodeLengthOfString: (NSString *) text
{
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++)
    {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    return asciiLength;
}

給UIView設(shè)置圖片

    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手勢覆蓋側(cè)滑手勢

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

去掉導(dǎo)航欄返回的back標(biāo)題

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];

字符串中是否含有中文

+ (BOOL)checkIsChinese:(NSString *)string
{
    for (int i=0; i<string.length; i++)
    {
        unichar ch = [string characterAtIndex:i];
        if (0x4E00 <= ch  && ch <= 0x9FA5)
        {
            return YES;
        }
    }
    return NO;
}

dispatch_group的使用

    dispatch_group_t dispatchGroup = dispatch_group_create();
    dispatch_group_enter(dispatchGroup);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"第一個請求完成");
        dispatch_group_leave(dispatchGroup);
    });
    
    dispatch_group_enter(dispatchGroup);
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"第二個請求完成");
        dispatch_group_leave(dispatchGroup);
    });
    
    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
        NSLog(@"請求完成");
    });

UITextField每四位加一個空格,實(shí)現(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;
}

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

//獲取私有屬性 比如設(shè)置UIDatePicker的字體顏色
- (void)setTextColor
{
    //獲取所有的屬性拦宣,去查看有沒有對應(yīng)的屬性
    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];
        //獲得屬性對應(yīng)的nsstring
        NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        //輸出打印看對應(yīng)的屬性
        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"];
    }
}

獲取手機(jī)安裝的應(yīng)用

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;//設(shè)置每周第一天從周一開始
    //計(jì)算兩個日期分別為這年第幾周
    NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
    NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
    
    //相等就在同一周,不相等就不在同一周
    return countSelf == countDate;
}

應(yīng)用內(nèi)打開系統(tǒng)設(shè)置界面

   //iOS8之后
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    //如果App沒有添加權(quán)限,顯示的是設(shè)定界面鸵隧。如果App有添加權(quán)限(例如通知)绸罗,顯示的是App的設(shè)定界面。
/iOS8之前
    //先添加一個url type如下圖豆瘫,在代碼中調(diào)用如下代碼,即可跳轉(zhuǎn)到設(shè)置頁面的對應(yīng)項(xiàng)
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=WIFI"]];
    
    可選值如下:
    About — prefs:root=General&path=About
    Accessibility — prefs:root=General&path=ACCESSIBILITY
    Airplane Mode On — prefs:root=AIRPLANE_MODE
    Auto-Lock — prefs:root=General&path=AUTOLOCK
    Brightness — prefs:root=Brightness
    Bluetooth — prefs:root=General&path=Bluetooth
    Date & Time — prefs:root=General&path=DATE_AND_TIME
    FaceTime — prefs:root=FACETIME
    General — prefs:root=General
    Keyboard — prefs:root=General&path=Keyboard
    iCloud — prefs:root=CASTLE
    iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
    International — prefs:root=General&path=INTERNATIONAL
    Location Services — prefs:root=LOCATION_SERVICES
    Music — prefs:root=MUSIC
    Music Equalizer — prefs:root=MUSIC&path=EQ
    Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
    Network — prefs:root=General&path=Network
    Nike + iPod — prefs:root=NIKE_PLUS_IPOD
    Notes — prefs:root=NOTES
    Notification — prefs:root=NOTIFICATI*****_ID
    Phone — prefs:root=Phone
    Photos — prefs:root=Photos
    Profile — prefs:root=General&path=ManagedConfigurationList
    Reset — prefs:root=General&path=Reset
    Safari — prefs:root=Safari
    Siri — prefs:root=General&path=Assistant
    Sounds — prefs:root=Sounds
    Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
    Store — prefs:root=STORE
    Twitter — prefs:root=TWITTER
    Usage — prefs:root=General&path=USAGE
    VPN — prefs:root=General&path=Network/VPN
    Wallpaper — prefs:root=Wallpaper
    Wi-Fi — prefs:root=WIFI

動畫暫停再開始

-(void)pauseLayer:(CALayer *)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

-(void)resumeLayer:(CALayer *)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

iOS中數(shù)字的格式化

//通過NSNumberFormatter珊蟀,同樣可以設(shè)置NSNumber輸出的格式。例如如下代碼:
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
    NSLog(@"Formatted number string:%@",string);
    //輸出結(jié)果為:[1223:403] Formatted number string:123,456,789
    
    //其中NSNumberFormatter類有個屬性numberStyle外驱,它是一個枚舉型育灸,設(shè)置不同的值可以輸出不同的數(shù)字格式。該枚舉包括:
    typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
        NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
        NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
        NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
        NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
        NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
        NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
    };
    //各個枚舉對應(yīng)輸出數(shù)字格式的效果如下:其中第三項(xiàng)和最后一項(xiàng)的輸出會根據(jù)系統(tǒng)設(shè)置的語言區(qū)域的不同而不同昵宇。
    [1243:403] Formatted number string:123456789
    [1243:403] Formatted number string:123,456,789
    [1243:403] Formatted number string:¥123,456,789.00
    [1243:403] Formatted number string:-539,222,988%
    [1243:403] Formatted number string:1.23456789E8
    [1243:403] Formatted number string:一億二千三百四十五萬六千七百八十九

如何獲取WebView所有的圖片地址
在網(wǎng)頁加載完成時磅崭,通過js獲取圖片和添加點(diǎn)擊的識別方式

//UIWebView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //這里是js,主要目的實(shí)現(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)榧兺该?/strong>

//第一種方法
    //導(dǎo)航欄純透明
    [self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去掉導(dǎo)航欄底部的黑線
    self.navigationBar.shadowImage = [UIImage new];
    
    //第二種方法
    [[self.navigationBar subviews] objectAtIndex:0].alpha = 0;

tabBar同理

[self.tabBar setBackgroundImage:[UIImage new]];self.tabBar.shadowImage = [UIImage new];

navigationBar根據(jù)滑動距離的漸變色實(shí)現(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ā)中一些相關(guān)的路徑

模擬器的位置:
    /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

獲取圖片的擴(kuò)展名

//通過圖片Data數(shù)據(jù)第一個字節(jié) 來獲取圖片擴(kuò)展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}

//調(diào)用
//假設(shè)這是一個網(wǎng)絡(luò)獲取的URL
NSString *path = @"http://pic.rpgsky.net/images/2016/07/26/3508cde5f0d29243c7d2ecbd6b9a30f1.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
//調(diào)用獲取圖片擴(kuò)展名
NSString *string = [self contentTypeForImageData:data];
//輸出結(jié)果為 png
NSLog(@"%@",string);

Button禁止觸摸事件的2種方式

//會改變按鈕的狀態(tài)蒋譬,顏色會變灰
button.enabled = NO;
//保持按鈕原來的狀態(tài)割岛,顏色不會變
button.userInteractionEnabled = NO;

如果在xib中有一個控件, 已經(jīng)明確設(shè)置尺寸了,輸出的frame也是對的, 但是顯示出來的效果不一樣(比如尺寸變大了), 如果是這種情況一般就是autoresizingMask自動伸縮屬性在搞鬼! 解決辦法如下:

//xib的awakeFromNib方法中設(shè)置UIViewAutoresizingNone進(jìn)行清空
- (void)awakeFromNib {
    self.autoresizingMask = UIViewAutoresizingNone;
}

設(shè)置圖片圓角

/** 設(shè)置圓形圖片(放到分類中使用) */
- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 獲取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 設(shè)置圓形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 將圖片畫上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市犯助,隨后出現(xiàn)的幾起案子癣漆,更是在濱河造成了極大的恐慌,老刑警劉巖也切,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扑媚,死亡現(xiàn)場離奇詭異腰湾,居然都是意外死亡雷恃,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門费坊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來倒槐,“玉大人,你說我怎么就攤上這事附井√衷剑” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵永毅,是天一觀的道長把跨。 經(jīng)常有香客問我,道長沼死,這世上最難降的妖魔是什么着逐? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上耸别,老公的妹妹穿的比我還像新娘健芭。我一直安慰自己,他們只是感情好秀姐,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布慈迈。 她就那樣靜靜地躺著,像睡著了一般省有。 火紅的嫁衣襯著肌膚如雪痒留。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天蠢沿,我揣著相機(jī)與錄音狭瞎,去河邊找鬼。 笑死搏予,一個胖子當(dāng)著我的面吹牛熊锭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播雪侥,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼碗殷,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了速缨?” 一聲冷哼從身側(cè)響起锌妻,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎旬牲,沒想到半個月后仿粹,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡原茅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年吭历,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片擂橘。...
    茶點(diǎn)故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡晌区,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出通贞,到底是詐尸還是另有隱情朗若,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布昌罩,位于F島的核電站哭懈,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏茎用。R本人自食惡果不足惜遣总,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一你虹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧彤避,春花似錦傅物、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至圆米,卻和暖如春卒暂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背娄帖。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工也祠, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人近速。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓诈嘿,卻偏偏與公主長得像,于是被迫代替她去往敵國和親削葱。 傳聞我的和親對象是個殘疾皇子奖亚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件析砸、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,105評論 4 62
  • 在這里總結(jié)一些iOS開發(fā)中的小技巧昔字,能大大方便我們的開發(fā) 原文地址:http://www.reibang.com/...
    Marray閱讀 333評論 0 0
  • 在這里總結(jié)一些iOS開發(fā)中的小技巧,能大大方便我們的開發(fā)首繁,持續(xù)更新作郭。 UITableView的Group樣式下頂部...
    UI愛好者閱讀 519評論 0 0
  • “那一天 陽光很好 風(fēng)也很好 你也很好 一切都是我喜歡的樣子” 即便是許多年后, 回想到初遇的那一天弦疮, 想必夹攒, 仍...
    孟惜良閱讀 258評論 0 0
  • 有些事芹助,當(dāng)它該來的時候,容不得你做任何充分準(zhǔn)備闲先,只得硬著頭皮上。也許一開始有些不習(xí)慣无蜂,有些慌張伺糠,但當(dāng)身臨其中,你就...
    檸檬香茶閱讀 164評論 1 2