美文网首页
iOS一些小细节(2)

iOS一些小细节(2)

作者: EdwardSelf | 来源:发表于2016-09-08 10:16 被阅读83次

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

}

}

}

相关文章

  • iOS一些小细节(2)

    1、app名称的修改 在info.plist中添加一个key(Bundle display name),Value...

  • iOS一些小细节(1)

    一边开发,一边记录,不积小流无以成江海~~每26条换一篇文章。 1、使用pch文件,要修改project文件里的b...

  • iOS tableview的一些小细节

    1.点击cell后点击状态消失 2.修改自带imageview的大小。注:这段代码要放到imageview.ima...

  • contentSize、contentInset和content

    这几个都是在ios程序中,经常会注意到的一些小细节,能否真正了解这些,对写ios程序也有很大的好处。frame 是...

  • contentSize、contentInset和content

    这几个都是在ios程序中,经常会注意到的一些小细节,能否真正了解这些,对写ios程序也有很大的好处。frame 是...

  • ios面试资料

    比较系统的知识库,包含基础知识和ios oc面试知识点 iosBAT面经-有些小细节待自己搜索答案iOS面试题系列...

  • 一些小细节

    他转脸看着江生说,“这是阿遇,我把他交给你,从今以后,你要拿命护着他。” 江生看了眼床边的杜遇,“杜先生放心,江生...

  • iOS开发 UITableView 常用细节

    iOS开发 UITableView 常用细节 iOS开发 UITableView 常用细节

  • iOS开发中@property的一些小细节

    @property是iOS开发中常见属性,下面写一点在开发中遇到的一些问题和心得。适合刚开始学习iOS的朋友提升一...

  • iOS一些小细节(3)(不断更新~)

    1、滚动隐藏或者显示导航栏 先声明两个属性 @property(nonatomic)CGFloatbeginCon...

网友评论

      本文标题:iOS一些小细节(2)

      本文链接:https://www.haomeiwen.com/subject/fbssettx.html