iOS一些小细节(2)

1、app名称的修改

在info.plist中添加一个key(Bundle display name),Value就是你需要的新名字,Run后退回主页面,可以看到你的新App名字在这页面上了。

2、获取某个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;
}

3、两种方法删除NSUserDefaults所有记录

   //方法一:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

   //方法二:

- (void)resetDefaults{

NSUserDefaults*defs = [NSUserDefaults standardUserDefaults];

NSDictionary* dic = [defs dictionaryRepresentation];

for(id key in dic) {

[defs removeObjectForKey:key];

}

[defssynchronize];

}


4、字符串反转

    第一种:

- (NSString*)reverseWordsInString:(NSString*)str{

NSMutableString*newString = [[NSMutableString alloc]initWithCapacity:str.length];

for(NSInteger i = str.length-1; i >=0; i--) {

unicharch = [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|NSStringEnumerationByComposedCharacterSequencesusingBlock:^(NSString*_Nullablesubstring,NSRangesubstringRange,NSRangeenclosingRange,BOOL*_Nonnullstop) {

[reverString appendString:substring];

}];

return reverString;

}

5、禁止锁屏

[UIApplication sharedApplication].idleTimerDisabled=YES;

或 [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

6、iOS跳转到AppStore下载应用评分

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

7、中文转拼音

- (NSString*)transform:(NSString*)chinese{

//将NSString转换成NSMutableString

NSMutableString *pinyin = [chinese mutableCopy];

//将汉字转换为拼音(带音标)

CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL,kCFStringTransformToLatin,NO);

NSLog(@"pin yin%@",pinyin);

//去掉拼音的音标

CFStringTransform((__bridgeCFMutableStringRef)pinyin,NULL,kCFStringTransformStripCombiningMarks,NO);

NSLog(@"qu yin biao%@", pinyin);

//返回最近结果

return pinyin;

}

8、手动更改iOS状态栏的颜色

- (void)setStatusBarBackgroundColor:(UIColor*)color{

UIView*statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

if([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {

statusBar.backgroundColor= color;

}

}

9、判断当前ViewController是push还是present的方式显示的

NSArray*viewControllers =self.navigationController.viewControllers;

if(viewControllers.count>1) {

if([viewControllrs objectAtIndex:viewControllers.count-1] ==self) {

//push方式

[self.navigationController popViewControllerAnimated:YES];

}

}

else{

//present方式

[self dismissViewControllerAnimated:YEScompletion:nil];

}

10、iOS在当前屏幕获取第一响应

UIWindow*keyWindow = [[UIApplication sharedApplication] keyWindow];

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

11、判断对象是否遵循了某协议

if([self.selectedController conformsToProtocol:@protocol(RefreshProtocol)]) {

[self.selectedController performSelector:@selector(onTriggerRefresh)];

}

12、判断view是不是指定视图的子视图

BOOL isView = [textView isDescendantOfView:self.view];

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

14、获取一个类的所有子类(需要引入runtime.h)

+ (NSArray*)allSubclasses{

Class myClass = [selfclass];

NSMutableArray*mySubclasses = [NSMutableArrayarray];

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) {

[mySubclassesaddObject:classes[ci]];

}

}

free(classes);

return mySubclasses;

}

15、取消UICollectionView的隐式动画

[UIViewperformWithoutAnimation:^{

[collectionView reloadItemsAtIndexPaths:@[indexpath indexpathForItem:index inSection:0]];

}];

16、UIImage占用内存大小

UIImage*image = [UIImageimageNamed:@"a"];

NSUIntegersize =CGImageGetHeight(image.CGImage) *CGBitmapContextGetBytesPerRow(image.CGImage);

17、GCD timer 定时器

dispatch_queue_tqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

dispatch_source_ttimer =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(), ^{

//回主线程

});

});

18、图片上绘制文字  属于UIImage的Category

- (UIImage*)imageWithTitle:(NSString*)title fontSize:(CGFloat)fontSize{

//画布大小

CGSizesize =CGSizeMake(self.size.width,self.size.height);

//创建一个基于位图的上下文

UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0

[selfdrawAtPoint:CGPointMake(0,0)];

//文字居中显示在画布上

NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle]mutableCopy];

paragraphStyle.lineBreakMode=NSLineBreakByCharWrapping;

paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中

//计算文字所占的size,文字居中显示在画布上

CGSizesizeText = [title boundingRectWithSize:self.sizeoptions:NSStringDrawingUsesLineFragmentOriginattributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;

CGFloatwidth =self.size.width;

CGFloatheight =self.size.height;

CGRectrect =CGRectMake((width - sizeText.width)/2, (height -sizeText.height)/2, sizeText.width, sizeText.height);

//绘制文字

[title drawInRect:rectwithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];

//返回绘制的新图形

UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returnnewImage;

}

19、查找一个视图的所有子视图

- (NSMutableArray*)allSubViewsForView:(UIView*)view{

NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];

for(UIView *subView in view.subviews) {

[array addObject:subView];

subviews.count>0) {

[array addObjectsFromArray:[self allSubViewsForView:subView]];

}

}

return array;

}


20、按比例缩放,size 是你要把图显示到 多大区域CGSizeMake(300, 140)

- (UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{

UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;

CGFloat width = imageSize.width;

CGFloat height = imageSize.height;

CGFloat targetWidth = size.width;

CGFloat targetHeight = size.height;

CGFloat scaleFactor = 0.0;

CGFloat scaledWidth = targetWidth;

CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);

if(CGSizeEqualToSize(imageSize, size) == NO){

CGFloat widthFactor = targetWidth / width;

CGFloat heightFactor = targetHeight / height;

if(widthFactor > heightFactor){

scaleFactor = widthFactor;

}

else{

scaleFactor = heightFactor;

}

scaledWidth = width * scaleFactor;

scaledHeight = height * scaleFactor;

if(widthFactor > heightFactor){

thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

}else if(widthFactor < heightFactor){

thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

}

}

UIGraphicsBeginImageContext(size);

CGRect thumbnailRect = CGRectZero;

thumbnailRect.origin = thumbnailPoint;

thumbnailRect.size.width = scaledWidth;

thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();

if(newImage == nil){

NSLog(@"scale image fail");

}

UIGraphicsEndImageContext();

return newImage;

}

  21、指定宽度按比例缩放

- (UIImage*) imageCompressForWidth:(UIImage*)sourceImage targetWidth:(CGFloat)defineWidth{

UIImage*newImage =nil;

CGSizeimageSize = sourceImage.size;

CGFloatwidth = imageSize.width;

CGFloatheight = imageSize.height;

CGFloattargetWidth = defineWidth;

CGFloattargetHeight = height / (width / targetWidth);

CGSizesize =CGSizeMake(targetWidth, targetHeight);

CGFloatscaleFactor =0.0;

CGFloatscaledWidth = targetWidth;

CGFloatscaledHeight = targetHeight;

CGPointthumbnailPoint =CGPointMake(0.0,0.0);

if(CGSizeEqualToSize(imageSize, size) ==NO){

CGFloatwidthFactor = targetWidth / width;

CGFloatheightFactor = targetHeight / height;

if(widthFactor > heightFactor){

scaleFactor = widthFactor;

}

else{

scaleFactor = heightFactor;

}

scaledWidth = width * scaleFactor;

scaledHeight = height * scaleFactor;

if(widthFactor > heightFactor){

thumbnailPoint.y= (targetHeight - scaledHeight) *0.5;

}elseif(widthFactor < heightFactor){

thumbnailPoint.x= (targetWidth - scaledWidth) *0.5;

}

}

UIGraphicsBeginImageContext(size);

CGRectthumbnailRect =CGRectZero;

thumbnailRect.origin= thumbnailPoint;

thumbnailRect.size.width= scaledWidth;

thumbnailRect.size.height= scaledHeight;

[sourceImagedrawInRect:thumbnailRect];

newImage =UIGraphicsGetImageFromCurrentImageContext();

if(newImage ==nil){

NSLog(@"scale image fail");

}

UIGraphicsEndImageContext();

return newImage;

}


22、textfield只能输入数字和小数点

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{

////控制长度

//if(range.location>=25)

//return NO;

constchar* ch = [stringcStringUsingEncoding:NSUTF8StringEncoding];

if(*ch == 0)

return YES;

//字符0-9和.

if( *ch !=46&& ( *ch <48|| *ch >57) ){

return NO;

}//有了小数点

if([textField.textrangeOfString:@"."].length==1)

{

NSUInteger length=[textField.textrangeOfString:@"."].location;

//小数点后面两位小数且不能再是小数点

if([[textField.textsubstringFromIndex:length] length]>3|| *ch ==46){//3表示后面小数位的个数。。

return NO;

}

}

return YES;

}


23、

如图

24、假设 i = 1 ,如果想用 i 除以100得到0.01的值:

i / 100.0 才会得到0.01。 整型除以浮点型,自动变浮点型。

25、把segment放在导航栏的中间

[self.navigationItem setTitleView:_segmentView];


26'//去掉UItableview headerview黏性(sticky)

- (void)scrollViewDidScroll:(UIScrollView*)scrollView {

if(scrollView ==self.mainTableView)

{

CGFloatsectionHeaderHeight =60;//sectionHeaderHeight

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

}

}

}

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

推荐阅读更多精彩内容