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(); // 關(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"];

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,622評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,716評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,746評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,991評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,706評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,036評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,029評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,203評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,725評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,451評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,677評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,161評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,857評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,266評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,606評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,407評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,643評論 2 380

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

  • 1、禁止手機(jī)睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa閱讀 1,139評論 1 6
  • 在iOS中隨處都可以看到絢麗的動畫效果,實(shí)現(xiàn)這些動畫的過程并不復(fù)雜,今天將帶大家一窺ios動畫全貌。在這里你可以看...
    每天刷兩次牙閱讀 8,551評論 6 30
  • 在iOS中隨處都可以看到絢麗的動畫效果,實(shí)現(xiàn)這些動畫的過程并不復(fù)雜,今天將帶大家一窺iOS動畫全貌。在這里你可以看...
    F麥子閱讀 5,140評論 5 13
  • #define kBlackColor [UIColor blackColor] //.h //劃線 + (voi...
    CHADHEA閱讀 811評論 0 1
  • 背景 最近在聽開言英語突然想到一個問題,為什么我們只是被動的聽他們聊美食聊生活的方方面面,而自己確很少想起自己應(yīng)該...
    shawnxjf閱讀 874評論 0 0