### 生成嵌入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(); // 關(guān)閉上下文 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加載時動畫的實(shí)現(xiàn)
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ //設(shè)置Cell的動畫效果為3D效果 //設(shè)置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); }];}
### 向下拖動顯示導(dǎo)航欄,向上拖動隱藏導(dǎo)航欄
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ //scrollView已經(jīng)有拖拽手勢,直接拿到scrollView的拖拽手勢 UIPanGestureRecognizer* pan = scrollView.panGestureRecognizer; //獲取到拖拽的速度 >0 向下拖動 <0 向上拖動 CGFloat velocity = [pan velocityInView:scrollView].y; if (velocity<-5) { //向上拖動,隱藏導(dǎo)航欄 [self.navigationController setNavigationBarHidden:true animated:true]; } else if (velocity>5) { //向下拖動,顯示導(dǎo)航欄 [self.navigationController setNavigationBarHidden:false animated:true]; } else if(velocity==0){ //停止拖拽 }}
### 直播點(diǎn)贊動畫的實(shí)現(xiàn)
-(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點(diǎn)擊動畫 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]; }]; }
### 心(點(diǎn)贊)的繪制
-(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];} ===========================================
### 阿拉伯?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 = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆",]; //有對應(yīng)關(guān)系,就想到要用字典 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];//添加數(shù)值單位 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); //創(chuàng)建一個基于位圖的上下文 UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0 [self drawAtPoint:CGPointMake(0.0,0.0)]; //文字居中顯示在畫布上NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping; paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中 //計算文字所占的size,文字居中顯示在畫布上 CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size; CGFloat width = self.size.width; CGFloat height = self.size.height; CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height); //繪制文字 [title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}]; //返回繪制的新圖形 UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage;}
### 文件大小的計算
//文件大小
- (long long)fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize; return size; } return 0;}//文件夾大小- (long long)folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager = [NSFileManager defaultManager]; long long folderSize = 0; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles = [fileManager subpathsAtPath:path];for (NSString *fileName in childerFiles) { NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName]; if ([fileManager fileExistsAtPath:fileAbsolutePath]) { long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize; folderSize += size; } } } return folderSize;}### UIView設(shè)置部分圓角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)建shapelayermasklayer.frame = view.bounds;masklayer.path = path.CGPath;//設(shè)置路徑view.layer.mask = masklayer;### 向上取整floor(x),有時候也寫做Floor(x),其功能是“下取整”,即取不大于x的最大整數(shù) 例如:x=3.14,floor(x)=3y=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.00floor函數(shù)與ceil函數(shù)的返回值均為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 //獲取私有屬性
比如設(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"]; } }
### 判斷兩個日期是否在同一周 寫在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è)置每周第一天從周一開始 //計算兩個日期分別為這年第幾周 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中數(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:一億二千三百四十五萬六千七百八十九
### navigationBar變?yōu)榧兺该?/p>
//第一種方法
//導(dǎo)航欄純透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];//去掉導(dǎo)航欄底部的黑線self.navigationBar.shadowImage = [UIImage new];
//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;### 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;}
### 常用宏
//計算最大值、最小值、絕對值
#define MAX(A,B) ((A) > (B) ? (A) : (B))#define MIN(A,B) ((A) < (B) ? (A) : (B))#define ABS(A) ((A) < 0 ? (-(A)) : (A))### runtime - 幾個常用的運(yùn)行時方法#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#>)// 設(shè)置關(guān)聯(lián)對象objc_setAssociatedObject(<#id object#>, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)// 獲取關(guān)聯(lián)對象objc_getAssociatedObject(<#id object#>, <#const void *key#>)// 給某個對象發(fā)送某個消息void objc_msgSend(void /* id self, SEL op, ... */ )
### iOS造輪子系列
-TableView空數(shù)據(jù)顯示占位圖片 runtime實(shí)現(xiàn)
@interface UITableView (placeholder)// hook Tabview的reloadData方法, 根據(jù)dataSource的數(shù)據(jù)來判斷是否顯示圖片/* 占位圖 */@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(@“點(diǎn)擊了無數(shù)據(jù)的圖片”); }];[_tableView reloadData];
### 幀循環(huán)
游戲其實(shí)就是不斷的繪制,不斷的處理事件來展示游戲的邏輯.動畫的本質(zhì)就是定時器+屬性的改變;[幀循環(huán)的累積效應(yīng)] 上述是屬性動畫,還有一種是幀動畫,是圖片一幀一幀的播放;
=========================================### OC與JS交互
主要是通過iOS7之后蘋果推出的JavaScriptCore框架* 首先是在H5頁面中注冊一個方法jsButton * 在webViewDidLoad方法中獲取JSContext對象JSContext *context = [webView valueForKeyPath:@“documentView.webView.mainFrame.javaScriptContext”];* 設(shè)置context, key對應(yīng)于在H5中的方法名,value對應(yīng)要執(zhí)行的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]; //將漢字轉(zhuǎn)換為拼音(帶音標(biāo)) CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO); //去掉音標(biāo) CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO); return pinyin;}
### 手動修改狀態(tài)欄的顏色
- (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或數(shù)字型的字符串,比如@"2.0"* 平均值@"avg.floatValue",最大值max,最小值min### 修改UITextField中placeholder的文字顏色[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];