iOS开发最佳实践总结

晚上下班回来经常盯着手机屏幕发呆,就想写点什么,打发下漫长的夜晚,并记录下工作中的点点滴滴。


这头像是不是很可爱

1.tableview选中到未选中动画处理

Views and View Controllers利用UIViewControllerTransitionCoordinator在UIViewController的转场动画中获取更精准的控制

Session只简单地提了一下,没有展开。
但是看到Session的这里,却引起了我的思考。让我想到了从iOS7开始,系统为UINavigationController添加了一个返回手势,只要我们在边缘用手势就能够返回。

但是有时会遇到一种情况,那就是我们在viewWillAppear里面做了一些工作。而一旦用户在手势滑动的过程中如果中途取消了。那么我们viewWillAppear里面的工作已经被触发了,但是下一次用户再滑动返回,仍然会触发一次。

举一个例子,直到我写下这篇总结时,苹果在其iOS的最新版本iOS10.2中仍然有的问题,不信你就拿手机试试。

那就是打开iOS设置界面,随便点一个比如通用一栏进去,然后我们滑动返回,能看到有个美妙的cell从selected到deselected的过渡动画。但是注意,如果我们中途取消返回,第二次返回的时候,就没有这个效果了。

中途取消返回,第二次返回的时候,就没有这个效果了

原因就在于第一次viewWillAppear的时候已经取消了选择。

这个问题我们就能通过UIViewControllerTransitionCoordinator来进行精确协调。
苹果官方文档说明

An object that adopts the UIViewControllerTransitionCoordinator protocol provides support for animations associated with a view controller transition. Typically, you do not adopt this protocol in your own classes. When you present or dismiss a view controller, UIKit creates a transition coordinator object automatically and assigns it to the view controller’s transitionCoordinator property. That transition coordinator object is ephemeral and lasts for the duration of the transition animation.

也就是ViewController本身会提供一个这样的Coordinator来帮助我们精确定位转场动画的状态。

上面的问题我们能够这样解决。重点在于检测到transition如果被取消的话,我们就恢复到原来的状态。除此之外我们还能够检测到过场的其他状态与属性。可以查阅 官方文档

关键在viewWillAppear的处理

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSIndexPath *indexpatch = self.tableView.indexPathForSelectedRow;
    if (indexpatch) {
        [self.tableView deselectRowAtIndexPath:indexpatch animated:YES];
        if (_theSwitch.isOn) {//开关打开时执行如下代码
            [self.transitionCoordinator notifyWhenInteractionChangesUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
                if ([context isCancelled]) {
                    [self.tableView selectRowAtIndexPath:indexpatch animated:YES scrollPosition:UITableViewScrollPositionNone];
                }
            }];
        }
    }
}
- (IBAction)switchChangeValue:(UISwitch *)sender {
    _statusLabel.text = sender.isOn ? @"动画开启😀":@"动画关闭☹️";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"网络请求---测试";
    titleArr = @[@"get请求",@"post请求",@"down请求"];
     _statusLabel.text = _theSwitch.isOn ? @"动画开启😀":@"动画关闭☹️";
}

有图有真相

体验都是从小细节做起的

2.避免使用setTag:和viewWithTag:

因为可能会导致

  • 与系统或是别人的tag冲突
  • 没有编译警告
  • 没有runtime errors
    其实我基本在工程里都没有用tag来标记View。一直都是使用property。所以没有注意到这个问题。看了这个Session之后也没有什么感觉。
直到有一天我在一个有几十万行代码的项目中还看到了这样的代码:
cellSubViewTag++;
UILabel* someLabel = (UILabel*)[cell.contentView viewWithTag:cellSubViewTag];
if (someLabel == nil) {
    someLabel = [[UILabel alloc] init];
    someLabel.tag = cellSubViewTag;
    [cell.contentView addSubview: someLabel];
}
cellSubViewTag++
//继续add subView.........

我整个人都不好了。因为新添加的业务需要我去取出某个Label的值,如果使用property。我只需要cell.someLabel.text去取这个值就好。这个时候。我只能看着这样的代码流泪重构。所以请大家务必在开发中使用property引用SubView。爱人爱己,在这里就应该老老实实地继承TableViewCell,在里面进行布局,暴露出应该暴露的变量供别人使用。

简单来说,就是不要因为便利而去牺牲可维护性,可扩展性和可阅读性。

3.Table and Collection Views一个Cell高度变化动画的技巧

如果我们采用了AutoLayout只需四步即可。
tableView.beginUpdates
Update model
Update cell contents
tableView.endUpdates

4.App Lifecycle如何使应用启动更快。

要点在于:

Return quickly from applicationDidFinishLaunching

在applicationDidFinishLaunching不要花费时间进行读取数据等工作,尽快地返回。如果有必要的话,让它在后台执行,不阻塞主线程。

例如:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        [self loadData];
    });
    return YES;
}

/** 耗时方法*/
- (void)loadData {
    //各种耗时  加载数据库。。。
}

我是分割线 ----好久没更新了

5.控件的局部圆角问题

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

CGRect rect = CGRectMake(0, 0, 100, 50);
    CGSize radio = CGSizeMake(5, 5);//圆角尺寸
    UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//这只圆角位置
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
    CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//创建shapelayer
    masklayer.frame = button.bounds;
    masklayer.path = path.CGPath;//设置路径
    button.layer.mask = masklayer;

举例为button,其它继承自UIView的控件都可以

6.navigationBar隐藏显示的过度

相信在使用中肯定遇到过,一个页面隐藏navigationBar,另一个不隐藏。两个页面进行push和pop的时候,尤其是有侧滑手势返回的时候,不做处理就会造成滑动返回时,navigationBar位置是空的,直接显示一个黑色或者显示下面一层视图,很难看。这就需要我们加入过度动画来隐藏或显示navigationBar:
在返回后将要出现的页面实现viewWillAppear方法,需要隐藏就设为YES,需要显示就设为NO

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

7.图片处理只拿到图片的一部分

UIImage *image = [UIImage imageNamed:filename];
CGImageRef imageRef = image.CGImage;
CGRect rect = CGRectMake(origin.x, origin.y ,size.width, size.height);
#这里的宽高是相对于图片的真实大小
#比如你的图片是400x400的那么(0,0,400,400)就是图片的全尺寸,想取哪一部分就设置相应坐标即可
CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, rect);
UIImage *imageRect = [[UIImage alloc] initWithCGImage:imageRefRect];

8.模态跳转的动画设置

设置模态跳转的动画,系统提供了四种可供选择

DetailViewController *detailVC = [[DetailViewController alloc]init];
    #//UIModalTransitionStyleFlipHorizontal 翻转
    #//UIModalTransitionStyleCoverVertical 底部滑出
    #//UIModalTransitionStyleCrossDissolve 渐显
    #//UIModalTransitionStylePartialCurl 翻页
    detailVC.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentViewController:detailVC animated:YES completion:nil];

9.navigationBar的透明问题

如果仅仅把navigationBar的alpha设为0的话,那就相当于把navigationBar给隐藏了,大家都知道,父视图的alpha设置为0的话,那么子视图全都会透明的。那么相应的navigationBar的标题和左右两个按钮都会消失。这样显然达不到我们要求的效果。

(1)如果仅仅是想要navigationBar透明,按钮和标题都在可以使用以下方法:

[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];//给navigationBar设置一个空的背景图片即可实现透明,而且标题按钮都在

细心的你会发现上面有一条线如下图:


有图为证

这就需要我们做进一步处理,把线去掉,如下方法即可:

self.navigationController.navigationBar.shadowImage = [UIImage new];
//其实这个线也是image控制的。设为空即可

(2)如果你想在透明的基础上实现根据下拉距离,由透明变得不透明的效果,那么上面那个就显得力不从心了,这就需要我们采用另外一种方法了

//navigationBar是一个复合视图,它是有许多个控件组成的,那么我们就可以从他的内部入手
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = 0;//这里可以根据scrollView的偏移量来设置alpha就实现了渐变透明的效果```
###10.给TableView或者CollectionView的cell添加简单动画
只要在willDisplayCell方法中对将要显示的cell做动画即可:
  • (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell )cell forRowAtIndexPath:(NSIndexPath)indexPath{
    NSArray *array = tableView.indexPathsForVisibleRows;
    NSIndexPath *firstIndexPath = array[0];

    //设置anchorPoint
    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    //为了防止cell视图移动,重新把cell放回原来的位置
    cell.layer.position = CGPointMake(0, cell.layer.position.y);

    //设置cell 按照z轴旋转90度,注意是弧度
    if (firstIndexPath.row < indexPath.row) {
    cell.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1.0);
    }else{
    cell.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 0, 1.0);
    }

    cell.alpha = 0.0;

    [UIView animateWithDuration:1 animations:^{
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1.0;
    }];
    }

  • (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cellforItemAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row % 2 != 0) {
    cell.transform = CGAffineTransformTranslate(cell.transform, kScreenWidth/2, 0);
    }else{
    cell.transform = CGAffineTransformTranslate(cell.transform, -kScreenWidth/2, 0);
    }
    cell.alpha = 0.0;
    [UIView animateWithDuration:0.7 animations:^{
    cell.transform = CGAffineTransformIdentity;
    cell.alpha = 1.0;
    } completion:^(BOOL finished) {

    }];
    }


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

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

UITableView的plain样式下,取消区头停滞效果
  • (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);
    }
    }
那个,其实,还是用Group样式吧哈哈。

#12.获取某个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;
    }
#13.两种方法删除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];
    }
#13.打印系统所有已注册的字体名称

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

void enumerateFonts()
{
for(NSString *familyName in [UIFont familyNames])
{
NSLog(@"%@",familyName);
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for(NSString *fontName in fontNames)
{
NSLog(@"\t|- %@",fontName);
}
}
}

#14.取图片某一像素点的颜色 在UIImage的分类中
  • (UIColor *)colorAtPixel:(CGPoint)point
    {
    if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point))
    {
    return nil;
    }

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * 1;
    NSUInteger bitsPerComponent = 8;
    unsigned char pixelData[4] = {0, 0, 0, 0};

    CGContextRef context = CGBitmapContextCreate(pixelData,
    1,
    1,
    bitsPerComponent,
    bytesPerRow,
    colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextSetBlendMode(context, kCGBlendModeCopy);

    CGContextTranslateCTM(context, -point.x, point.y - self.size.height);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), self.CGImage);
    CGContextRelease(context);

    CGFloat red = (CGFloat)pixelData[0] / 255.0f;
    CGFloat green = (CGFloat)pixelData[1] / 255.0f;
    CGFloat blue = (CGFloat)pixelData[2] / 255.0f;
    CGFloat alpha = (CGFloat)pixelData[3] / 255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    }

#15.字符串反转

第一种:
  • (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;
    }
#16.禁止锁屏,

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

[UIApplication sharedApplication].idleTimerDisabled = YES;

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

#17.模态推出透明界面

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

#18.Xcode调试不显示内存占用

editSCheme 里面有个选项叫叫做enable zoombie Objects 取消选中

#19.显示隐藏文件

//显示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder

//隐藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder

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

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

#21.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;
    }
#22.手动更改iOS状态栏的颜色
  • (void)setStatusBarBackgroundColor:(UIColor *)color
    {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
    {
    statusBar.backgroundColor = color;
    }
    }
    判断当前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];
}

#23.获取实际使用的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;
    }
#24.iOS在当前屏幕获取第一响应

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

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

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

#26.判断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);

#27.修改UITextField中Placeholder的文字颜色

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

#28.关于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: 毫秒

#29.获取一个类的所有子类
  • (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;
    }

#30.监测IOS设备是否设置了代理,需要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(@"设置了代理");
}

#31.阿拉伯数字转中文格式

+(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;

}

#32.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 = [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);

#33.取消UICollectionView的隐式动画

UICollectionView在reloadItems的时候,默认会附加一个隐式的fade动画,有时候很讨厌,尤其是当你的cell是复合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];
}];

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

打开终端输入三条命令:
touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o "target stop-hook disable" >> ~/.lldbinit

#35.CocoaPods pod install/pod update更新慢的问题

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

#36.UIImage 占用内存大小

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

#37.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); //每秒执行
dispatch_source_set_event_handler(timer, ^{
//@"倒计时结束,关闭"
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{

});

});
dispatch_resume(timer);

#38.图片上绘制文字 写一个UIImage的category
  • (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
    {
    //画布大小
    CGSize size=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 = [[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;
    }

#39.查找一个视图的所有子视图
  • (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;
    }
#40.计算文件大小

//文件大小

  • (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;
    }

#41.UIView设置部分圆角

你是不是也遇到过这样的问题,一个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];//创建shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;//设置路径
view.layer.mask = masklayer;

#42.取上整与取下整

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型

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

//方法一:

  • (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;
}

#44.给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);

#45.防止scrollView手势覆盖侧滑手势

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

#46.去掉导航栏返回的back标题

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

#47.字符串中是否含有中文
  • (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;
    }
#48.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(@"请求完成");
});
#49.UITextField每四位加一个空格,实现代理
  • (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;
    }
#50.获取私有属性和成员变量 #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"];
    }
    }
#51.获取手机安装的应用

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

#52.判断两个日期是否在同一周 写在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;
    }

#53.应用内打开系统设置界面

//iOS8之后
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App没有添加权限,显示的是设定界面。如果App有添加权限(例如通知),显示的是App的设定界面。
//iOS8之前
//先添加一个url type如下图,在代码中调用如下代码,即可跳转到设置页面的对应项
[[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

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

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

#55.动画暂停再开始

-(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;
}

#56.iOS中数字的格式化

//通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt: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] 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:一亿二千三百四十五万六千七百八十九

#57.如何获取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<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的数组
    }
    //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];

#58.navigationBar变为纯透明

//第一种方法
//导航栏纯透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉导航栏底部的黑线
self.navigationBar.shadowImage = [UIImage new];

//第二种方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
tabBar同理

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

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

//第一种

  • (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;
    }

#60.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/Provisioning Profiles

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

一般情况下,右边的item会和屏幕右侧保持一段距离:
下面是通过添加一个负值宽度的固定间距的item来解决,也可以改变宽度实现不同的间隔:

UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//宽度为负数的固定间距的系统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];

#62.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:[NSCharacterSet URLQueryAllowedCharacterSet]];

//解码 打印:http://abc.com?aaa=你好&bbb=tttee
string = [string stringByRemovingPercentEncoding];
UIWebView设置User-Agent。

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

#63.获取硬盘总容量与可用容量:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary *attributes = [fileManager attributesOfFileSystemForPath:NSHomeDirectory() error:nil];

NSLog(@"容量%.2fG",[attributes[NSFileSystemSize] doubleValue] / (powf(1024, 3)));
NSLog(@"可用%.2fG",[attributes[NSFileSystemFreeSize] doubleValue] / powf(1024, 3));

#64.获取UIColor的RGBA值

UIColor *color = [UIColor colorWithRed: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.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

#65.AFN移除JSON中的NSNull

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

#66.ceil()和floor()

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

#67.UIWebView里面的图片自适应屏幕

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

  • (void)webViewDidFinishLoad:(UIWebView *)webView
    {
    NSString *js = @"function imgAutoFit() {
    var imgs = document.getElementsByTagName('img');
    for (var i = 0; i < imgs.length; ++i) {
    var img = imgs[i];
    img.style.maxWidth = %f;
    }
    }";

    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];

    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    }

持续更新中……。

未完,待续...
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,126评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,254评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,445评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,185评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,178评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,970评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,276评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,927评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,400评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,883评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,997评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,646评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,213评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,204评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,423评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,423评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,722评论 2 345

推荐阅读更多精彩内容