iOS常用代码集

### 生成嵌入logo的二维码

-(void)buildAppCIImageWithinImageView:(UIImageView *)imageView mappingUrl:(NSString *)url{ //生成APP下载地址的二维码 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; [filter setDefaults]; NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding]; [filter setValue:data forKeyPath:@"inputMessage"]; CIImage *outputImage = [filter outputImage]; outputImage = [outputImage imageByApplyingTransform:CGAffineTransformMakeScale(20, 20)]; UIImage *image = [UIImage imageWithCIImage:outputImage]; // 添加自定义Logo UIImage *smallImage = [UIImage imageNamed:@"appIcon"]; UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; [smallImage drawInRect:CGRectMake((image.size.width - 100) / 2, (image.size.width - 100) / 2, 100, 100)]; // 获取最终的图片 UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); // 关闭上下文 UIGraphicsEndImageContext(); // 显示 imageView.image = finalImage; }### 自定义形状请用Core Graphics框架来绘图- (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextMoveToPoint(context, rect.origin.x, rect.origin.y);CGContextAddLineToPoint(context, rect.size.width, 0); CGContextAddLineToPoint(context, rect.size.width, rect.size.width); CGContextClosePath(context); CGContextSetFillColorWithColor(context, [UIColor colorWithRed:30/255.0 green:130/255.0 blue:210/255.0 alpha:1].CGColor); CGContextFillPath(context); // 画椭圆 // CGContextAddEllipseInRect(context, rect); }

### cell加载时动画的实现

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ //设置Cell的动画效果为3D效果 //设置x和y的初始值为0.1 cell.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1); //x和y的最终值为1 [UIView animateWithDuration:1 animations:^{ cell.layer.transform = CATransform3DMakeScale(1, 1, 1); }];}

### 向下拖动显示导航栏,向上拖动隐藏导航栏

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ //scrollView已经有拖拽手势,直接拿到scrollView的拖拽手势 UIPanGestureRecognizer* pan = scrollView.panGestureRecognizer; //获取到拖拽的速度 >0 向下拖动 <0 向上拖动 CGFloat velocity = [pan velocityInView:scrollView].y; if (velocity<-5) { //向上拖动,隐藏导航栏 [self.navigationController setNavigationBarHidden:true animated:true]; } else if (velocity>5) { //向下拖动,显示导航栏 [self.navigationController setNavigationBarHidden:false animated:true]; } else if(velocity==0){ //停止拖拽 }}

### 直播点赞动画的实现

-(void)showTheLove:(UIButton *)sender{ DMHeartFlyView* heart = [[DMHeartFlyView alloc]initWithFrame:CGRectMake(0, 0, _heartSize, _heartSize)]; [self.view addSubview:heart]; CGPoint fountainSource = CGPointMake(([UIScreen mainScreen].bounds.size.width-_heartSize-10)/2 + _heartSize/2.0, self.view.bounds.size.height - _heartSize/2.0 - 10); heart.center = fountainSource; [heart animateInView:self.view]; // button点击动画 CAKeyframeAnimation *btnAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"]; btnAnimation.values = @[@(1.0),@(0.7),@(0.5),@(0.3),@(0.5),@(0.7),@(1.0), @(1.2), @(1.4), @(1.2), @(1.0)]; btnAnimation.keyTimes = @[@(0.0),@(0.1),@(0.2),@(0.3),@(0.4),@(0.5),@(0.6),@(0.7),@(0.8),@(0.9),@(1.0)]; btnAnimation.calculationMode = kCAAnimationLinear; btnAnimation.duration = 0.3; [sender.layer addAnimation:btnAnimation forKey:@"SHOW"];}-(void)animateInView:(UIView *)view{ NSTimeInterval totalAnimationDuration = 6; CGFloat heartSize = CGRectGetWidth(self.bounds); CGFloat heartCenterX = self.center.x; CGFloat viewHeight = CGRectGetHeight(view.bounds); //Pre-Animation setup self.transform = CGAffineTransformMakeScale(0, 0); self.alpha = 0; //Bloom [UIView animateWithDuration:0.5 delay:0.0 usingSpringWithDamping:0.6 initialSpringVelocity:0.8 options:UIViewAnimationOptionCurveEaseOut animations:^{ self.transform = CGAffineTransformIdentity; self.alpha = 0.9; } completion:NULL]; NSInteger i = arc4random_uniform(2); NSInteger rotationDirection = 1- (2*i);// -1 OR 1 NSInteger rotationFraction = arc4random_uniform(10); [UIView animateWithDuration:totalAnimationDuration animations:^{self.transform = CGAffineTransformMakeRotation(rotationDirection * PI/(16 + rotationFraction*0.2)); } completion:NULL]; UIBezierPath *heartTravelPath = [UIBezierPath bezierPath]; [heartTravelPath moveToPoint:self.center]; //random end point CGPoint endPoint = CGPointMake(heartCenterX + (rotationDirection) * arc4random_uniform(2*heartSize), viewHeight/6.0 + arc4random_uniform(viewHeight/4.0)); //random Control Points NSInteger j = arc4random_uniform(2); NSInteger travelDirection = 1- (2*j);// -1 OR 1 //randomize x and y for control points CGFloat xDelta = (heartSize/2.0 + arc4random_uniform(2*heartSize)) * travelDirection; CGFloat yDelta = MAX(endPoint.y ,MAX(arc4random_uniform(8*heartSize), heartSize)); CGPoint controlPoint1 = CGPointMake(heartCenterX + xDelta, viewHeight - yDelta); CGPoint controlPoint2 = CGPointMake(heartCenterX - 2*xDelta, yDelta); [heartTravelPath addCurveToPoint:endPoint controlPoint1:controlPoint1 controlPoint2:controlPoint2]; CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; keyFrameAnimation.path = heartTravelPath.CGPath; keyFrameAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; keyFrameAnimation.duration = totalAnimationDuration + endPoint.y/viewHeight; [self.layer addAnimation:keyFrameAnimation forKey:@"positionOnPath"]; //Alpha & remove from superview [UIView animateWithDuration:totalAnimationDuration animations:^{self.alpha = 0.0; } completion:^(BOOL finished) { [self removeFromSuperview]; }]; }

### 心(点赞)的绘制

-(void)drawHeartInRect:(CGRect)rect{ [_strokeColor setStroke]; [_fillColor setFill]; CGFloat drawingPadding = 4.0; CGFloat curveRadius = floor((CGRectGetWidth(rect) - 2*drawingPadding) / 4.0); //Creat path UIBezierPath *heartPath = [UIBezierPath bezierPath]; //Start at bottom heart tip CGPoint tipLocation = CGPointMake(floor(CGRectGetWidth(rect) / 2.0), CGRectGetHeight(rect) - drawingPadding); [heartPath moveToPoint:tipLocation]; //Move to top left start of curve CGPoint topLeftCurveStart = CGPointMake(drawingPadding, floor(CGRectGetHeight(rect) / 2.4)); [heartPath addQuadCurveToPoint:topLeftCurveStart controlPoint:CGPointMake(topLeftCurveStart.x, topLeftCurveStart.y + curveRadius)]; //Create top left curve [heartPath addArcWithCenter:CGPointMake(topLeftCurveStart.x + curveRadius, topLeftCurveStart.y) radius:curveRadius startAngle:PI endAngle:0 clockwise:YES]; //Create top right curve CGPoint topRightCurveStart = CGPointMake(topLeftCurveStart.x + 2*curveRadius, topLeftCurveStart.y); [heartPath addArcWithCenter:CGPointMake(topRightCurveStart.x + curveRadius, topRightCurveStart.y) radius:curveRadius startAngle:PI endAngle:0 clockwise:YES]; //Final curve to bottom heart tip CGPoint topRightCurveEnd = CGPointMake(topLeftCurveStart.x + 4*curveRadius, topRightCurveStart.y); [heartPath addQuadCurveToPoint:tipLocation controlPoint:CGPointMake(topRightCurveEnd.x, topRightCurveEnd.y + curveRadius)]; [heartPath fill]; heartPath.lineWidth = 1; heartPath.lineCapStyle = kCGLineCapRound; heartPath.lineJoinStyle = kCGLineCapRound; [heartPath stroke];} ===========================================

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

+ (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]; return chinese;}

### 图片上绘制文字

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

### 文件大小的计算

//文件大小

- (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设置部分圆角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];//创建shapelayermasklayer.frame = view.bounds;masklayer.path = path.CGPath;//设置路径view.layer.mask = masklayer;### 向上取整floor(x),有时候也写做Floor(x),其功能是“下取整”,即取不大于x的最大整数 例如:x=3.14,floor(x)=3y=9.99999,floor(y)=9与floor函数对应的是ceil函数,即上取整函数。ceil函数的作用是求不小于给定实数的最小整数。ceil(2)=ceil(1.2)=cei(1.5)=2.00floor函数与ceil函数的返回值均为double型

### 计算字符串的字符长度

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

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

#import //获取私有属性

比如设置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"]; } }

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

### 动画暂停再开始

-(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中数字的格式化

//通过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:一亿二千三百四十五万六千七百八十九

### navigationBar变为纯透明

//第一种方法

//导航栏纯透明

[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//去掉导航栏底部的黑线self.navigationBar.shadowImage = [UIImage new];

//第二种方法

[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;### 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;}

### 常用宏

//计算最大值、最小值、绝对值

#define MAX(A,B) ((A) > (B) ? (A) : (B))#define MIN(A,B) ((A) < (B) ? (A) : (B))#define ABS(A) ((A) < 0 ? (-(A)) : (A))### runtime - 几个常用的运行时方法#import // 获得某个类的类方法Method class_getClassMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)// 获得某个类的对象方法Method class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>)// 方法交换void method_exchangeImplementations(<#Method m1#>, <#Method m2#>)// 拷贝某个类的所有成员变量class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)// 设置关联对象objc_setAssociatedObject(<#id object#>, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)// 获取关联对象objc_getAssociatedObject(<#id object#>, <#const void *key#>)// 给某个对象发送某个消息void objc_msgSend(void /* id self, SEL op, ... */ )

### iOS造轮子系列

-TableView空数据显示占位图片 runtime实现

@interface UITableView (placeholder)// hook Tabview的reloadData方法, 根据dataSource的数据来判断是否显示图片/* 占位图 */@property (nonatomic, strong) UIView *placeHolderView;@end#import "UITableView+placeholder.h"

#import @implementation NSObject (swizzle)+ (void)swizzleInstanceSelector:(SEL)originalSel WithSwizzledSelector:(SEL)swizzledSel{ Method originMethod = class_getInstanceMethod(self, originalSel); Method swizzedMehtod = class_getInstanceMethod(self, swizzledSel); BOOL methodAdded = class_addMethod(self, originalSel, method_getImplementation(swizzedMehtod), method_getTypeEncoding(swizzedMehtod)); if (methodAdded) { class_replaceMethod(self, swizzledSel, method_getImplementation(originMethod), method_getTypeEncoding(originMethod)); }else{ method_exchangeImplementations(originMethod, swizzedMehtod); }}@end@implementation UITableView (placeholder)+ (void)load{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self swizzleInstanceSelector:@selector(reloadData) WithSwizzledSelector:@selector(gy_reloadData)]; });}- (void)setPlaceHolderView:(UIView *)placeHolderView{ objc_setAssociatedObject(self, @selector(placeHolderView), placeHolderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}- (UIView *)placeHolderView{ return objc_getAssociatedObject(self, @selector(placeHolderView));}- (void)gy_reloadData{ [self gy_checkEmpty]; [self gy_reloadData];}- (void)gy_checkEmpty{ BOOL isEmpty = YES; id src = self.dataSource; NSInteger sections = 1; if ([src respondsToSelector:@selector(numberOfSectionsInTableView:)]) { sections = [src numberOfSectionsInTableView:self]; } for (int i = 0; i < sections; i++) { NSInteger rows = [src tableView:self numberOfRowsInSection:i]; if (rows) { isEmpty = NO; } } if (isEmpty) { [self.placeHolderView removeFromSuperview]; [self addSubview:self.placeHolderView]; }else{ [self.placeHolderView removeFromSuperview]; }}_tableView.placeHolderView = [[GYNoDataView alloc] initWithFrame:self.view.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{ NSLog(@“点击了无数据的图片”); }];[_tableView reloadData];

### 帧循环

游戏其实就是不断的绘制,不断的处理事件来展示游戏的逻辑.动画的本质就是定时器+属性的改变;[帧循环的累积效应] 上述是属性动画,还有一种是帧动画,是图片一帧一帧的播放;

=========================================### OC与JS交互

主要是通过iOS7之后苹果推出的JavaScriptCore框架* 首先是在H5页面中注册一个方法jsButton * 在webViewDidLoad方法中获取JSContext对象JSContext *context = [webView valueForKeyPath:@“documentView.webView.mainFrame.javaScriptContext”];* 设置context, key对应于在H5中的方法名,value对应要执行的OC方法体context["jsButton"] = ^{ NSLog(@"haha"); };

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

UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 1)];self.tableView.tableHeaderView = view;* 去掉表视图尾部的空白行self.tableView.tableFooterView = [[UIView alloc]init];### 获取某个view所在的控制器- (UIViewController *)viewController{ UIViewController *viewController = nil; UIResponder *next = self.view.nextResponder; while (next) { if ([next isKindOfClass:[UIViewController class]]) { viewController = (UIViewController *)next; break; } next = next.nextResponder; } return viewController;}

### 获取汉字的拼音

+ (NSString *)transform:(NSString *)chinese{ NSMutableString *pinyin = [chinese mutableCopy]; //将汉字转换为拼音(带音标) CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); //去掉音标 CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); return pinyin;}

### 手动修改状态栏的颜色

- (void)setStatusBarBackgroundColor:(UIColor *)color{ UIView *statusBar = [[UIApplication sharedApplication] valueForKeyPath:@"statusBarWindow.statusBar"]; if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { [statusBar setBackgroundColor:color]; }}

### NSArray快速求和

NSArray *array = @[@(1.0),@(2.3),@(3.0),@(4.4),@(2.0)];CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];* 注:array中的元素为NSNumber或数字型的字符串,比如@"2.0"* 平均值@"avg.floatValue",最大值max,最小值min### 修改UITextField中placeholder的文字颜色[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

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

推荐阅读更多精彩内容

  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,084评论 1 6
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 8,321评论 6 30
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 5,001评论 5 13
  • #define kBlackColor [UIColor blackColor] //.h //划线 + (voi...
    CHADHEA阅读 750评论 0 1
  • 背景 最近在听开言英语突然想到一个问题,为什么我们只是被动的听他们聊美食聊生活的方方面面,而自己确很少想起自己应该...
    shawnxjf阅读 780评论 0 0