值得收藏的iOS开发常用代码块
遍历可变数组的同时删除数组元素
NSMutableArray*copyArray=[NSMutableArrayarrayWithArray:array];
NSString*str1=@“zhangsan”;
for(AddressPerson*perNameincopyArray){
if([[perNamename]isEqualToString:str1]){
[arrayremoveObject:perName];
}
}
获取系统当前语言
NSString*currentLanguage=[[NSLocalepreferredLanguages]objectAtIndex:0];
NSLog(@"currentlanguage=%@",currentLanguage);
if([currentLanguagecontainsString:@"zh-Hans"]){
NSLog(@"zh-Hans简体中文");
}elseif([currentLanguagecontainsString:@"zh-Hant"]){
NSLog(@"zh-Hant繁体中文");
}
UITableView的Group样式下顶部空白处理
UIView*view=[[UIViewalloc]initWithFrame:CGRectMake(0,0,0,0.1)]; self.tableView.tableHeaderView=view;
UITableView的plain样式下,取消区头停滞效果
-(void)scrollViewDidScroll:(UIScrollView*)scrollView
{
CGFloatsectionHeaderHeight=sectionHead.height;
if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView;.contentOffset.y>=0)
{
scrollView.contentInset=UIEdgeInsetsMake(-scrollView.contentOffset.y,0,0,0);
}
elseif(scrollView.contentOffset.y>=sectionHeaderHeight)
{
scrollView.contentInset=UIEdgeInsetsMake(-sectionHeaderHeight,0,0,0);
}
}
获取某个view所在的控制器
-(UIViewController*)viewController
{
UIViewController*viewController=nil;
UIResponder*next=self.nextResponder;
while(next)
{
if([nextisKindOfClass:[UIViewControllerclass]])
{
viewController=(UIViewController*)next;
break;
}
next=next.nextResponder;
}
returnviewController;
}
两种方法删除NSUserDefaults所有记录
//方法一
NSString*appDomain=[[NSBundlemainBundle]bundleIdentifier];
[[NSUserDefaultsstandardUserDefaults]removePersistentDomainForName:appDomain];
//方法二
-(void)resetDefaults
{
NSUserDefaults*defs=[NSUserDefaultsstandardUserDefaults];
NSDictionary*dict=[defsdictionaryRepresentation];
for(idkeyindict)
{
[defsremoveObjectForKey:key];
}
[defssynchronize];
}
打印系统所有已注册的字体名称
voidenumerateFonts()
{
for(NSString*familyNamein[UIFontfamilyNames])
{
NSLog(@"%@",familyName);
NSArray*fontNames=[UIFontfontNamesForFamilyName:familyName];
for(NSString*fontNameinfontNames)
{
NSLog(@"\t|-%@",fontName);
}
}
}
获取图片某一点的颜色
-(UIColor*)getPixelColorAtLocation:(CGPoint)pointinImage:(UIImage*)image
{
UIColor*color=nil;
CGImageRefinImage=image.CGImage;
CGContextRefcgctx=[selfcreateARGBBitmapContextFromImage:inImage];
if(cgctx==NULL){
returnnil;/*error*/
}
size_tw=CGImageGetWidth(inImage);
size_th=CGImageGetHeight(inImage);
CGRectrect={{0,0},{w,h}};
CGContextDrawImage(cgctx,rect,inImage);
unsignedchar*data=CGBitmapContextGetData(cgctx);
if(data!=NULL){
intoffset=4*((w*round(point.y))+round(point.x));
intalpha=data[offset];
intred=data[offset+1];
intgreen=data[offset+2];
intblue=data[offset+3];
color=[UIColorcolorWithRed:(red/255.0f)green:(green/255.0f)blue:
(blue/255.0f)alpha:(alpha/255.0f)];
}
CGContextRelease(cgctx);
if(data){
free(data);
}
returncolor;
}
字符串反转
//第一种:
-(NSString*)reverseWordsInString:(NSString*)str
{
NSMutableString*newString=[[NSMutableStringalloc]initWithCapacity:str.length];
for(NSIntegeri=str.length-1;i>=0;i--)
{
unicharch=[strcharacterAtIndex:i];
[newStringappendFormat:@"%c",ch];
}
returnnewString;
}
//第二种:
-(NSString*)reverseWordsInString:(NSString*)str
{
NSMutableString*reverString=[NSMutableStringstringWithCapacity:str.length];
[strenumerateSubstringsInRange:NSMakeRange(0,str.length)options:NSStringEnumerationReverse|NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString*substring,NSRangesubstringRange,NSRangeenclosingRange,BOOL*stop){
[reverStringappendString:substring];
}];
returnreverString;
}
禁止锁屏
//第一种 [UIApplicationsharedApplication].idleTimerDisabled=YES; //第二种 [[UIApplicationsharedApplication]setIdleTimerDisabled:YES];
模态推出透明界面
UIViewController*vc=[[UIViewControlleralloc]init];
UINavigationController*na=[[UINavigationControlleralloc]initWithRootViewController:vc];
if([[[UIDevicecurrentDevice]systemVersion]floatValue]>=8.0)
{
na.modalPresentationStyle=UIModalPresentationOverCurrentContext;
}
else
{
self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[selfpresentViewController:naanimated:YEScompletion:nil];
iOS跳转到AppStore下载应用评分
[[UIApplicationsharedApplication]openURL:[NSURLURLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
手动更改iOS状态栏的颜色
-(void)setStatusBarBackgroundColor:(UIColor*)color
{
UIView*statusBar=[[[UIApplicationsharedApplication]valueForKey:@"statusBarWindow"]valueForKey:@"statusBar"];
if([statusBarrespondsToSelector:@selector(setBackgroundColor:)])
{
statusBar.backgroundColor=color;
}
}
判断当前ViewController是push还是present的方式显示
NSArray*viewcontrollers=self.navigationController.viewControllers;
if(viewcontrollers.count>1)
{
if([viewcontrollersobjectAtIndex:viewcontrollers.count-1]==self)
{
//push方式
[self.navigationControllerpopViewControllerAnimated:YES];
}
}
else
{
//present方式
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
获取实际使用的LaunchImage图片
-(NSString*)getLaunchImageName
{
CGSizeviewSize=self.window.bounds.size;
//竖屏
NSString*viewOrientation=@"Portrait";
NSString*launchImageName=nil;
NSArray*imagesDict=[[[NSBundlemainBundle]infoDictionary]valueForKey:@"UILaunchImages"];
for(NSDictionary*dictinimagesDict)
{
CGSizeimageSize=CGSizeFromString(dict[@"UILaunchImageSize"]);
if(CGSizeEqualToSize(imageSize,viewSize)&&[viewOrientationisEqualToString:dict[@"UILaunchImageOrientation"]])
{
launchImageName=dict[@"UILaunchImageName"];
}
}
returnlaunchImageName;
}
iOS在当前屏幕获取第一响应
UIWindow*keyWindow=[[UIApplicationsharedApplication]keyWindow]; UIView*firstResponder=[keyWindowperformSelector:@selector(firstResponder)];
判断对象是否遵循了某协议
if([self.selectedControllerconformsToProtocol:@protocol(RefreshPtotocol)])
{
[self.selectedControllerperformSelector:@selector(onTriggerRefresh)];
}
判断view是不是指定视图的子视图
BOOLisView=[textViewisDescendantOfView:self.view];
NSArray快速求总和最大值最小值和平均值
NSArray*array=[NSArrayarrayWithObjects:@"2.0",@"2.3",@"3.0",@"4.0",@"10",nil]; CGFloatsum=[[arrayvalueForKeyPath:@"@sum.floatValue"]floatValue]; CGFloatavg=[[arrayvalueForKeyPath:@"@avg.floatValue"]floatValue]; CGFloatmax=[[arrayvalueForKeyPath:@"@max.floatValue"]floatValue]; CGFloatmin=[[arrayvalueForKeyPath:@"@min.floatValue"]floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
修改UITextField中Placeholder的文字颜色
[textFieldsetValue:[UIColorredColor]forKeyPath:@"_placeholderLabel.textColor"];
获取一个类的所有子类
+(NSArray*)allSubclasses
{
ClassmyClass=[selfclass];
NSMutableArray*mySubclasses=[NSMutableArrayarray];
unsignedintnumOfClasses;
Class*classes=objc_copyClassList(&numOfClasses;);
for(unsignedintci=0;ci<numOfClasses;ci++)
{
ClasssuperClass=classes[ci];
do{
superClass=class_getSuperclass(superClass);
}while(superClass&&superClass!=myClass);
if(superClass)
{
[mySubclassesaddObject:classes[ci]];
}
}
free(classes);
returnmySubclasses;
}
阿拉伯数字转中文格式
+(NSString*)translation:(NSString*)arebic
{
NSString*str=arebic;
NSArray*arabic_numerals=@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
NSArray*chinese_numerals=@[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray*digits=@[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
NSDictionary*dictionary=[NSDictionarydictionaryWithObjects:chinese_numeralsforKeys:arabic_numerals];
NSMutableArray*sums=[NSMutableArrayarray];
for(inti=0;i<str.length;i++){
NSString*substr=[strsubstringWithRange:NSMakeRange(i,1)];
NSString*a=[dictionaryobjectForKey:substr];
NSString*b=digits[str.length-i-1];
NSString*sum=[astringByAppendingString:b];
if([aisEqualToString:chinese_numerals[9]])
{
if([bisEqualToString:digits[4]]||[bisEqualToString:digits[8]])
{
sum=b;
if([[sumslastObject]isEqualToString:chinese_numerals[9]])
{
[sumsremoveLastObject];
}
}else
{
sum=chinese_numerals[9];
}
if([[sumslastObject]isEqualToString:sum])
{
continue;
}
}
[sumsaddObject:sum];
}
NSString*sumStr=[sumscomponentsJoinedByString:@""];
NSString*chinese=[sumStrsubstringToIndex:sumStr.length-1];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
returnchinese;
}
取消UICollectionView的隐式动画
//方法一
[UIViewperformWithoutAnimation:^{
[collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
}];
//方法二
[UIViewanimateWithDuration:0animations:^{
[collectionViewperformBatchUpdates:^{
[collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
}completion:nil];
}];
//方法三
[UIViewsetAnimationsEnabled:NO];
[self.trackPanelperformBatchUpdates:^{
[collectionViewreloadItemsAtIndexPaths:@[[NSIndexPathindexPathForItem:indexinSection:0]]];
}completion:^(BOOLfinished){
[UIViewsetAnimationsEnabled:YES];
}];
判断邮箱格式是否正确的代码
-(BOOL)isValidateEmail:(NSString*)email
{
NSString*emailRegex=@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate*emailTest=[NSPredicatepredicateWithFormat:@"SELFMATCHES%@",emailRegex];
return[emailTestevaluateWithObject:email];
}
iOS中UITextField的字数限制
//在viewDidLoad中注册<UITextFieldTextDidChangeNotification>通知
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(textFiledEditChanged:)
name:@"UITextFieldTextDidChangeNotification"object:myTextField];
//实现监听方法
#pragmamark-NotificationMethod
-(void)textFieldEditChanged:(NSNotification*)obj
{
UITextField*textField=(UITextField*)obj.object;
NSString*toBeString=textField.text;
//获取高亮部分
UITextRange*selectedRange=[textFieldmarkedTextRange];
UITextPosition*position=[textFieldpositionFromPosition:selectedRange.startoffset:0];
//没有高亮选择的字,则对已输入的文字进行字数统计和限制
if(!position)
{
if(toBeString.length>MAX_STARWORDS_LENGTH)
{
NSRangerangeIndex=[toBeStringrangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if(rangeIndex.length==1)
{
textField.text=[toBeStringsubstringToIndex:MAX_STARWORDS_LENGTH];
}
else
{
NSRangerangeRange=[toBeStringrangeOfComposedCharacterSequencesForRange:NSMakeRange(0,MAX_STARWORDS_LENGTH)];
textField.text=[toBeStringsubstringWithRange:rangeRange];
}
}
}
}
小伙伴们,今天就分享到这里,下期更精彩!