ios开发中的小技巧

时间:2021-07-05 05:32:01

在这里总结一些iOS开发中的小技巧,能大大方便我们的开发,持续更新。

UITableView的Group样式下顶部空白处理

//分组列表头部空白处理
UIView *view = [[UIViewalloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;

UITableView的plain样式下,取消区头停滞效果

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloatsectionHeaderHeight = sectionHead.height;
    if (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);
    }
}

那个,其实,还是用Group样式吧哈哈。

获取某个view所在的控制器

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

两种方法删除NSUserDefaults所有记录

//方法一
NSString *appDomain = [[NSBundlemainBundle] bundleIdentifier];
[[NSUserDefaultsstandardUserDefaults] removePersistentDomainForName:appDomain];
 
 
//方法二
- (void)resetDefaults
{
    NSUserDefaults * defs = [NSUserDefaultsstandardUserDefaults];
    NSDictionary * dict = [defsdictionaryRepresentation];
    for (idkeyin dict)
    {
        [defsremoveObjectForKey:key];
    }
    [defssynchronize];
}

打印系统所有已注册的字体名称

#pragma mark - 打印系统所有已注册的字体名称
void enumerateFonts()
{
    for(NSString *familyNamein [UIFontfamilyNames])
  {
        NSLog(@"%@",familyName);              
        NSArray *fontNames = [UIFontfontNamesForFamilyName:familyName];      
        for(NSString *fontNamein fontNames)
      {
            NSLog(@"\t|- %@",fontName);
      }
  }
}

获取图片某一点的颜色

- (UIColor*) getPixelColorAtLocation:(CGPoint)pointinImage:(UIImage *)image
{
 
    UIColor* color = nil;
    CGImageRefinImage = image.CGImage;
    CGContextRefcgctx = [self createARGBBitmapContextFromImage:inImage];
 
    if (cgctx == NULL) {
        return nil; /* error */
    }
    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRectrect = {{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 = [UIColorcolorWithRed:(red/255.0f) green:(green/255.0f) blue:
                (blue/255.0f) alpha:(alpha/255.0f)];
    }
    CGContextRelease(cgctx);
    if (data) {
        free(data);
    }
    return color;
}

字符串反转

第一种:
- (NSString *)reverseWordsInString:(NSString *)str
{    
    NSMutableString *newString = [[NSMutableStringalloc] initWithCapacity:str.length];
    for (NSInteger i = str.length - 1; i >= 0 ; i --)
    {
        unicharch = [strcharacterAtIndex:i];      
        [newStringappendFormat:@"%c", ch];    
    }    
    return newString;
}
 
//第二种:
- (NSString*)reverseWordsInString:(NSString*)str
{    
    NSMutableString *reverString = [NSMutableStringstringWithCapacity:str.length];    
    [strenumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences  usingBlock:^(NSString *substring, NSRangesubstringRange, NSRangeenclosingRange, BOOL *stop) {
          [reverStringappendString:substring];                        
      }];    
    return reverString;
}

禁止锁屏,

默认情况下,当设备一段时间没有触控动作时,iOS会锁住屏幕。但有一些应用是不需要锁屏的,比如视频播放器。

[UIApplicationsharedApplication].idleTimerDisabled = YES;

[[UIApplicationsharedApplication] setIdleTimerDisabled:YES];

模态推出透明界面

UIViewController *vc = [[UIViewControlleralloc] init];
UINavigationController *na = [[UINavigationControlleralloc] initWithRootViewController:vc];
 
if ([[[UIDevicecurrentDevice] systemVersion] floatValue] >= 8.0)
{
    na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}
else
{
    self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
 
[self presentViewController:naanimated:YEScompletion:nil];

Xcode调试不显示内存占用

editSCheme  里面有个选项叫叫做enablezoombieObjects  取消选中

显示隐藏文件

//显示
defaultswritecom.apple.finderAppleShowAllFiles -bool true
killallFinder
 
//隐藏
defaultswritecom.apple.finderAppleShowAllFiles -bool false
killallFinder

字符串按多个符号分割

ios开发中的小技巧

iOS跳转到App Store下载应用评分

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

iOS 获取汉字的拼音

+ (NSString *)transform:(NSString *)chinese
{    
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinesemutableCopy];    
    //将汉字转换为拼音(带音标)    
    CFStringTransform((__bridgeCFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);    
    NSLog(@"%@", pinyin);    
    //去掉拼音的音标    
    CFStringTransform((__bridgeCFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);    
    NSLog(@"%@", pinyin);    
    //返回最近结果    
    return pinyin;
}

手动更改iOS状态栏的颜色

- (void)setStatusBarBackgroundColor:(UIColor *)color
{
    UIView *statusBar = [[[UIApplicationsharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
 
    if ([statusBarrespondsToSelector:@selector(setBackgroundColor:)])
    {
        statusBar.backgroundColor = color;    
    }
}

判断当前ViewController是push还是present的方式显示的

NSArray *viewcontrollers=self.navigationController.viewControllers;
 
if (viewcontrollers.count > 1)
{
    if ([viewcontrollersobjectAtIndex:viewcontrollers.count - 1] == self)
    {
        //push方式
      [self.navigationControllerpopViewControllerAnimated:YES];
    }
}
else
{
    //present方式
    [self dismissViewControllerAnimated:YEScompletion:nil];
}

获取实际使用的LaunchImage图片

- (NSString *)getLaunchImageName
{
    CGSizeviewSize = self.window.bounds.size;
    // 竖屏    
    NSString *viewOrientation = @"Portrait";  
    NSString *launchImageName = nil;    
    NSArray* imagesDict = [[[NSBundlemainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dictin imagesDict)
    {
        CGSizeimageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientationisEqualToString:dict[@"UILaunchImageOrientation"]])
        {
            launchImageName = dict[@"UILaunchImageName"];        
        }    
    }    
    return launchImageName;
}

iOS在当前屏幕获取第一响应

UIWindow * keyWindow = [[UIApplicationsharedApplication] keyWindow];
UIView * firstResponder = [keyWindowperformSelector:@selector(firstResponder)];

判断对象是否遵循了某协议

if ([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)])
{
    [self.selectedControllerperformSelector:@selector(onTriggerRefresh)];
}

判断view是不是指定视图的子视图

BOOL isView = [textViewisDescendantOfView:self.view];

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

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

修改UITextField中Placeholder的文字颜色

[textFieldsetValue:[UIColorredColor] forKeyPath:@"_placeholderLabel.textColor"];

关于NSDateFormatter的格式

G: 公元时代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,显示为1-12
MMM: 月,显示为英文月份简写,如 Jan
MMMM: 月,显示为英文月份全称,如 Janualy
dd: 日,2位数表示,如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 = [NSMutableArrayarray];
    unsigned int numOfClasses;
    Class *classes = objc_copyClassList(&numOfClasses;);
    for (unsigned int ci = 0; ci

监测IOS设备是否设置了代理,需要CFNetwork.framework

NSDictionary *proxySettings = (__bridgeNSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridgeNSArray *)(CFNetworkCopyProxiesForURL((__bridgeCFURLRef_Nonnull)([NSURLURLWithString:@"http://www.baidu.com"]), (__bridgeCFDictionaryRef_Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);
 
NSDictionary *settings = proxies[0];
NSLog(@"%@",[settingsobjectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settingsobjectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settingsobjectForKey:(NSString *)kCFProxyTypeKey]);
 
if ([[settingsobjectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
    NSLog(@"没代理");
}
else
{
    NSLog(@"设置了代理");
}

阿拉伯数字转中文格式

+(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 = [NSDictionarydictionaryWithObjects:chinese_numeralsforKeys:arabic_numerals];
 
    NSMutableArray *sums = [NSMutableArrayarray];
    for (int i = 0; i

Base64编码与NSString对象或NSData对象的转换

// Create NSData object
NSData *nsdata = [@"iOS Developer Tips encoded in Base64"
  dataUsingEncoding:NSUTF8StringEncoding];
 
// Get NSString from NSData object in Base64
NSString *base64Encoded = [nsdatabase64EncodedStringWithOptions:0];
 
// Print the Base64 encoded string
NSLog(@"Encoded: %@", base64Encoded);
 
// Let's go the other way...
 
// NSData from the Base64 encoded str
NSData *nsdataFromBase64String = [[NSDataalloc]
  initWithBase64EncodedString:base64Encodedoptions:0];
 
// Decoded NSString from the NSData
NSString *base64Decoded = [[NSStringalloc]
  initWithData:nsdataFromBase64Stringencoding:NSUTF8StringEncoding];
NSLog(@"Decoded: %@", base64Decoded);

取消UICollectionView的隐式动画

UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合cell的情况下(比如cell使用到了UIStackView)。

下面几种方法都可以帮你去除这些动画

//方法一
[UIViewperformWithoutAnimation:^{
    [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
}];
 
//方法二
[UIViewanimateWithDuration:0 animations:^{
    [collectionViewperformBatchUpdates:^{
        [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
    } completion:nil];
}];
 
//方法三
[UIViewsetAnimationsEnabled:NO];
[self.trackPanelperformBatchUpdates:^{
    [collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
} completion:^(BOOL finished) {
    [UIViewsetAnimationsEnabled:YES];
}];

让Xcode的控制台支持LLDB类型的打印

打开终端输入三条命令:
touch ~/.lldbinit
echodisplay @importUIKit >> ~/.lldbinit
echotargetstop-hookadd -o \"targetstop-hookdisable\" >> ~/.lldbinit

CocoaPods pod install/pod update更新慢的问题

podinstall --verbose --no-repo-update
podupdate --verbose --no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少

UIImage 占用内存大小

UIImage *image = [UIImageimageNamed:@"aa"];
NSUIntegersize  = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);

GCD timer定时器

dispatch_queue_tqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_ttimer = 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); //每秒执行
dispatch_source_set_event_handler(timer, ^{
    //@"倒计时结束,关闭"
    dispatch_source_cancel(timer);
    dispatch_async(dispatch_get_main_queue(), ^{
 
    });
});
dispatch_resume(timer);

图片上绘制文字 写一个UIImage的category

- (UIImage *)imageWithTitle:(NSString *)titlefontSize:(CGFloat)fontSize
{
    //画布大小
    CGSizesize=CGSizeMake(self.size.width,self.size.height);
    //创建一个基于位图的上下文
    UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO  scale:0.0
 
    [self drawAtPoint:CGPointMake(0.0,0.0)];
 
    //文字居中显示在画布上
    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyledefaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
 
    //计算文字所占的size,文字居中显示在画布上
    CGSizesizeText=[titleboundingRectWithSize:self.sizeoptions:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize]}context:nil].size;
    CGFloatwidth = self.size.width;
    CGFloatheight = self.size.height;
 
    CGRectrect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
    //绘制文字
    [titledrawInRect:rectwithAttributes:@{ NSFontAttributeName:[UIFontsystemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColorwhiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
 
    //返回绘制的新图形
    UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

查找一个视图的所有子视图

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

计算文件大小

//文件大小
- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManagerdefaultManager];
 
    if ([fileManagerfileExistsAtPath:path])
    {
        long long size = [fileManagerattributesOfItemAtPath:patherror:nil].fileSize;
        return size;
    }
 
    return 0;
}
 
//文件夹大小
- (long long)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManagerdefaultManager];
 
    long long folderSize = 0;
 
    if ([fileManagerfileExistsAtPath:path])
    {
        NSArray *childerFiles = [fileManagersubpathsAtPath:path];
        for (NSString *fileNamein childerFiles)
        {
            NSString *fileAbsolutePath = [pathstringByAppendingPathComponent:fileName];
            if ([fileManagerfileExistsAtPath:fileAbsolutePath])
            {
                long long size = [fileManagerattributesOfItemAtPath:fileAbsolutePatherror:nil].fileSize;
                folderSize += size;
            }
        }
    }
 
    return folderSize;
}

UIView设置部分圆角

你是不是也遇到过这样的问题,一个button或者label,只要右边的两个角圆角,或者只要一个圆角。该怎么办呢。这就需要图层蒙版来帮助我们了

CGRectrect = view.bounds;
CGSizeradio = CGSizeMake(30, 30);//圆角尺寸
UIRectCornercorner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置
UIBezierPath *path = [UIBezierPathbezierPathWithRoundedRect:rectbyRoundingCorners:cornercornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayeralloc]init];//创建shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;//设置路径
view.layer.mask = masklayer;

取上整与取下整

floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
 
与floor函数对应的是ceil函数,即上取整函数。
 
ceil函数的作用是求不小于给定实数的最小整数。
ceil(2)=ceil(1.2)=cei(1.5)=2.00
 
floor函数与ceil函数的返回值均为double型

计算字符串字符长度,一个汉字算两个字符

//方法一:
- (int)convertToInt:(NSString*)strtemp
{
    int strlength = 0;
    char* p = (char*)[strtempcStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i

给UIView设置图片

UIImage *image = [UIImageimageNamed:@"image"];
self.MYView.layer.contents = (__bridgeid_Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);

防止scrollView手势覆盖侧滑手势

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

去掉导航栏返回的back标题

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

字符串中是否含有中文

+ (BOOL)checkIsChinese:(NSString *)string
{
    for (int i=0; i

dispatch_group的使用

 dispatch_group_tdispatchGroup = 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每四位加一个空格,实现代理

- (BOOL)textField:(UITextField *)textFieldshouldChangeCharactersInRange:(NSRange)rangereplacementString:(NSString *)string
{
    // 四位加一个空格
    if ([string isEqualToString:@""])
    {
        // 删除字符
        if ((textField.text.length - 2) % 5 == 0)
        {
            textField.text = [textField.textsubstringToIndex:textField.text.length - 1];
        }
        return YES;
    }
    else
    {
        if (textField.text.length % 5 == 0)
        {
            textField.text = [NSStringstringWithFormat:@"%@ ", textField.text];
        }
    }
    return YES;
}

获取私有属性和成员变量 #import

//获取私有属性 比如设置UIDatePicker的字体颜色
- (void)setTextColor
{
    //获取所有的属性,去查看有没有对应的属性
    unsigned int count = 0;
    objc_property_t *propertys = class_copyPropertyList([UIDatePickerclass], &count);
    for(int i = 0;i
//获得成员变量 比如修改UIAlertAction的按钮字体颜色
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([UIAlertActionclass], &count);
    for(int i =0;i

获取手机安装的应用

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

判断两个日期是否在同一周 写在NSDate的category里面

- (BOOL)isSameDateWithDate:(NSDate *)date
{
    //日期间隔大于七天之间返回NO
    if (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
    {
        return NO;
    }
 
    NSCalendar *calender = [NSCalendarcurrentCalendar];
    calender.firstWeekday = 2;//设置每周第一天从周一开始
    //计算两个日期分别为这年第几周
    NSUIntegercountSelf = [calenderordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:self];
    NSUIntegercountDate = [calenderordinalityOfUnit:NSCalendarUnitWeekdayinUnit:NSCalendarUnitYearforDate:date];
 
    //相等就在同一周,不相等就不在同一周
    return countSelf == countDate;
}

应用内打开系统设置界面

//iOS8之后
[[UIApplicationsharedApplication] openURL:[NSURLURLWithString:UIApplicationOpenSettingsURLString]];
//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
//iOS8之前
//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项
[[UIApplicationsharedApplication] openURL:[NSURLURLWithString:@"prefs:root=WIFI"]];
 
可选值如下:
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
AirplaneModeOn — 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
iCloudStorage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
LocationServices — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
MusicEqualizer — prefs:root=MUSIC&path=EQ
MusicVolumeLimit — 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
SoftwareUpdate — 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

ios开发中的小技巧

屏蔽触发事件,2秒后取消屏蔽

[[UIApplicationsharedApplication] beginIgnoringInteractionEvents];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [[UIApplicationsharedApplication] endIgnoringInteractionEvents]
});

动画暂停再开始

-(void)pauseLayer:(CALayer *)layer
{
    CFTimeIntervalpausedTime = [layerconvertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}
 
-(void)resumeLayer:(CALayer *)layer
{
    CFTimeIntervalpausedTime = [layertimeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeIntervaltimeSincePause = [layerconvertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}

fillRule原理

ios开发中的小技巧

iOS中数字的格式化

//通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:
NSNumberFormatter *formatter = [[NSNumberFormatteralloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatterstringFromNumber:[NSNumbernumberWithInt:123456789]];
NSLog(@"Formatted number string:%@",string);
//输出结果为:[1223:403] Formatted number string:123,456,789
 
//其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:
typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
    NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
    NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
    NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
    NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
    NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
    NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
};
//各个枚举对应输出数字格式的效果如下:其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同。
[1243:403] Formattednumberstring:123456789
[1243:403] Formattednumberstring:123,456,789
[1243:403] Formattednumberstring:¥123,456,789.00
[1243:403] Formattednumberstring:-539,222,988%
[1243:403] Formattednumberstring:1.23456789E8
[1243:403] Formattednumberstring:一亿二千三百四十五万六千七百八十九

如何获取WebView所有的图片地址,

在网页加载完成时,通过js获取图片和添加点击的识别方式

//UIWebView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //这里是js,主要目的实现对url的获取
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i
//WKWebView
- (void)webView:(WKWebView *)webViewdidFinishNavigation:(null_unspecifiedWKNavigation *)navigation
{
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i

获取到webview的高度

CGFloatheight = [[self.webViewstringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

navigationBar变为纯透明

//第一种方法
//导航栏纯透明
[self.navigationBarsetBackgroundImage:[UIImagenew] forBarMetrics:UIBarMetricsDefault];
//去掉导航栏底部的黑线
self.navigationBar.shadowImage = [UIImagenew];
 
//第二种方法
[[self.navigationBarsubviews] objectAtIndex:0].alpha = 0;

tabBar同理

[self.tabBarsetBackgroundImage:[UIImagenew]];
self.tabBar.shadowImage = [UIImagenew];

navigationBar根据滑动距离的渐变色实现

//第一种
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloatoffsetToShow = 200.0;//滑动多少就完全显示
    CGFloatalpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
    [[self.navigationController.navigationBarsubviews] objectAtIndex:0].alpha = alpha;
}
//第二种
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloatoffsetToShow = 200.0;
    CGFloatalpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
 
    [self.navigationController.navigationBarsetShadowImage:[UIImagenew]];
    [self.navigationController.navigationBarsetBackgroundImage:[self imageWithColor:[[UIColororangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}
 
//生成一张纯色的图片
- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRectrect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRefcontext = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [colorCGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
 
    return theImage;
}

iOS 开发中一些相关的路径

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

navigationItem的BarButtonItem如何紧靠屏幕右边界或者左边界?

一般情况下,右边的item会和屏幕右侧保持一段距离:

ios开发中的小技巧

下面是通过添加一个负值宽度的固定间距的item来解决,也可以改变宽度实现不同的间隔:

UIImage *img = [[UIImageimageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//宽度为负数的固定间距的系统item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItemalloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpacetarget:nilaction:nil];
[rightNegativeSpacersetWidth:-15];
 
UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItemalloc]initWithImage:imgstyle:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItemalloc]initWithImage:imgstyle:UIBarButtonItemStylePlaintarget:selfaction:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];

ios开发中的小技巧

NSString进行URL编码和解码

NSString *string = @"http://abc.com?aaa=你好&bbb=tttee";
 
//编码 打印:http://abc.com?aaa=%E4%BD%A0%E5%A5%BD&bbb=tttee
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
 
//解码 打印:http://abc.com?aaa=你好&bbb=tttee
string = [string stringByRemovingPercentEncoding];

UIWebView设置User-Agent。

//设置
NSDictionary *dic = @{@"UserAgent":@"your UserAgent"};
[[NSUserDefaultsstandardUserDefaults] registerDefaults:dic];
//获取
NSString *agent = [self.WebViewstringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

获取硬盘总容量与可用容量:

NSFileManager *fileManager = [NSFileManagerdefaultManager];
NSDictionary *attributes = [fileManagerattributesOfFileSystemForPath:NSHomeDirectory() error:nil];
 
NSLog(@"容量%.2fG",[attributes[NSFileSystemSize] doubleValue] / (powf(1024, 3)));
NSLog(@"可用%.2fG",[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024, 3));

获取UIColor的RGBA值

UIColor *color = [UIColorcolorWithRed:0.2 green:0.3 blue:0.9 alpha:1.0];
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSLog(@"Red: %.1f", components[0]);
NSLog(@"Green: %.1f", components[1]);
NSLog(@"Blue: %.1f", components[2]);
NSLog(@"Alpha: %.1f", components[3]);

修改textField的placeholder的字体颜色、大小

[self.textFieldsetValue:[UIColorredColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textFieldsetValue:[UIFontboldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

AFN移除JSON中的NSNull

AFJSONResponseSerializer *response = [AFJSONResponseSerializerserializer];
response.removesKeysWithNullValues = YES;

ceil()和floor()

ceil() 功 能:返回大于或者等于指定表达式的最小整数

floor() 功 能:返回小于或者等于指定表达式的最大整数

UIWebView里面的图片自适应屏幕

在webView加载完的代理方法里面这样写:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i