ios常用小技巧

1、打印view所有子视图


1、打开终端输入一下三条命令:

touch ~/.lldbinit

echo display @import UIKit >> ~/.lldbinit

echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

输入完没有任何显示就表示成功了,可以打上断点并在控制台输入相关命令查看层级关系,如:

po self.view.frame(打印当前视图的frame)

po [[self view]recursiveDescription](打印所有视图的层级关系)

2、layoutSubviews调用时机


当视图第一次显示的时候会被调用

当这个视图显示在屏幕上了,点击按钮

添加子视图也会调用这个方法

当本视图的大小发生改变时,也会调用这个方法

当子视图的frame发生改变时,也会调用这个方法

当删除子视图时会调用方法

3、NSString过滤特殊字符


//定义一个特殊字符的集合

NSCharaterSet *set = [NSCharaterSet charaterSetWithCharaterInString:

@"@/:;(}{}][//\\@#$%$#%$%@#!@#"];

//过滤字符串的特殊字符

NSString *newString = [trimString stringByTrimmingCharacterInSet:set];

4、TranForm属性


//平移按钮

CGAffineTransform transForm = self.buttonView.transform;

self.buttonView.transform = CGAffineTransformRotate(transForm, 10, 0 );

//旋转按钮

self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4 );

//缩放按钮

self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化复位

self.buttonView.transform = CGAffineTransformIdentity;

5、去掉分割线多余15像素

//首先在viewDidLoad方法加入以下代码

if ([self.tableView respondsToSelector:@selector(setSparatorInset:)]) {

         [self.tableView setSeparatorInset:UIEdgeInsetZero];

}

if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {

         [self.tableView setLayoutMargins:UIEdgesetsZero];

}

然后在重写willDisplaycell方法

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cellforRowAtIndexPath:(NSIndexPath *)indexPath {

        if ([cell reaspondsToSelector:@selector(setSeparatorInset:)]) {

                   [cell setSeparatorInset:UIEdgeInsetsZero];

        }

        if ([cell respondsToselector:@selector(setLayoutMargins:)]) { 

                   [cell setLayoutMargrgins:UIEdgeInsetsZero];

        }

}

6、计算方法耗时时间间隔

//获取时间间隔

#define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

#define TOCK NSLog(@“Time: %f , CFAbsoluteTimeGetCurrent()-start”)

7、Color颜色宏定义

//随机颜色

#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0  green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

//颜色(RGB)

#define RGBCOLOR(r , g , b)  [UIColor colorWithRed:(r) / 255.0f  green:(g) / 255.0f    blue:(b) / 255.0f    alpha:1]

//利用这种方法设置颜色和透明度,可不影响子视图背景色

#define RGBACOLOR(r , g , b , a)  [UIColor colorWithRed:(r)/255.0f   green:(g)/255.0f  blue:(b)/255.0f   alpha:(a)];

8、Alert提示宏定义

#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show]

9、让ios应用直接退出

- (void)exitApplication {

        AppDelegate *app = [UIApplication sharedApplication].delegate;

        UIWindow *window = app.window;

        [UIView animateWithDuration:1.0f animations:^{

              window.alpha = 0;

        } completion:^(BOOL finished) {

              exit:(0);

       }];

}

10、NSArray快速求总和 最大值 最小值和平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];

CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];

CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];

CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];

CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];

NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

11、修改Label中不同文字颜色


- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{

     [self edotStringColor:Self.label.text editStr:@"好" color:[UIColor blueColor]];

}

- (void) edotStringColor:(NSString *)string editStr:(NSString*)edotStr color:(UIColor*)color{

//string为整体字符串,editStr为需要修改的字符串

    NSRange rande = [string rangeOfString:editStr];

    NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc]             initWithString:striking];

    [attribute addAttributes:@{NSForegroundColorAttributeName:color} rande:range];

    self.label.attributedText = attribute;

}

12、播放声音


#import

//1.获取音效资源的路径

NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];

//2.将路径转化为url

NSURL *tempUrl = [NSURL fileURLWithPath:path];

//3.用转化为的url创建一个播放器

NSError *error = nil;

AVAudioPlayer *play = [[AVAudioPlayer alloc] initWithContentsOfURL:tempUrl error:&error];

self.player = play;

//4.播放

[play play];

13、检测是否IPad Pro

- (BOOL)ispadPro {

UIScreen *Screen = [UIScreen mainScreen];

CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;

CGFloat height = Screen.nativeBouns.size.height/Screen.nativeScale;

BOOL islpad  = [[UIDevice currentDevice] userlnterfaceldiom] == UIUserInterfaceIdiomPad;

BOOL hasIPadProWidth  = fabs(width  - 1024.f) < DBL xss = removed xss=removed xss = removeed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed>> ~/.lldbinit

echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

}

14、Label行间距

- (void) test { 

NSMutableAttributedString *attributedString = [[NSMutableAttributtedString alloc] initWithString:self.contentLabel.text];

NSMutableParagraghStyle*paragraphStyle = [[NSMutableParagraphStyle alloc] init];

[garagraphStyle setLineSpacing:3];

//调整行间距

[attributedString addAttribute:NSParagraphStyleAttributeName  value:paragraphStyle  range:NSMakeRange(0,[self.contentLabel.text length])];

self.contentLabel.attributedText = attributedString;

}

15、UIIMageView填充模式

@"UIViewContentModeScaleTofill", // 拉伸自适应填满整个视图

@"UIViewContentModeScaleAspetFit" // 自适应比例大小显示

@"UIViewContentModeScaleAspectFill" // 原始大小显示

@"UIViewContentModeRedraw", // 尺寸改变时重绘

@"UIViewContentModeCenter",// 中间

@"UIViewContentModeTop",//顶部

@"UIViewContentModeBottom",//底部

@"UIViewContentModeLeft",//中间贴左

@"UIViewContentModeRight",//中间贴右

@"UIViewContentModeTopLeft",          // 贴左上

@"UIViewContentModeTopRight",        // 贴右上

@"UIViewContentModeBottomLeft",      // 贴左下

@"UIViewContentModeBottomRight",      // 贴右下

16、Debug栏自动把Unicode编码转化为汉字

DXXcodeConsoleUnicodePlugin 插件

17、设置状态栏文字样式颜色

[UIAppliction sharedApplication] setStatusBarHidden :NO];

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

18、字符串的相关操作


//去除所有的空格

[str stringByReplacingOccurrencesOfString:@" " withString:@""];

//去掉首尾的空格

[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

- (NSString *)uppercaseString;//全部字符转化为大写字母

- (NSString *)lowercaseString;//全部字符转化为小写字母

19、解决tableview的分割线短一截

-(void)viewDidLayoutSubviews{

if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])

{

{[self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];

}

if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])

{

[self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];

}

}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

if ([cell respondsToSelector:@selector(setSeparatorInset:)])

{

[cell setSeparatorInset:UIEdgeInsetsZero];

}

if ([cell respondsToSelector:@selector(setLayoutMargins:)])

{

[cell setLayoutMargins:UIEdgeInsetsZero];

}

}

20、动态隐藏NavigationBar

//当我们的手离开屏幕时候隐藏

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

if(velocity.y > 0)

}

[self.navigationController setNavigationBarHidden:YES animated:YES];

} else {

[self.navigationController setNavigationBarHidden:NO animated:YES];

}

}

velocity.y这个量,在上滑和下滑时,变化极小(小数),但是因为方向不同,有正负之分,这就很好处理了。

//在滑动过程中隐藏

self.navigationController.hidesBarsOnSwipe = YES;

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

CGFloat offsetY = scrollView.contentOffset.y + __tableView.contentInset.top;

CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.tableView].y;

if (offsetY > 64) {

if (panTranslationY > 0)

{

//下滑趋势,显示

[self.navigationController setNavigationBarHidden:NO animated:YES];

} else {

//上滑趋势,隐藏

[self.navigationController setNavigationBarHidden:YES animated:YES];

}

} else {

[self.navigationController setNavigationBarHidden:NO animated:YES];

}

}

这里的offsetY > 64只是为了在视图滑过navigationBar的高度之后才开始处理,防止影响展示效果。panTranslationY是scrollView的pan手势的手指位置的y值,可能不是太好,因为panTranslationY这个值在较小幅度上下滑动时,可能都为正或都为负,这就使得这一方式不太灵敏.

参照地址:http://blog.cocoachina.com/article/28221

你可能感兴趣的:(ios常用小技巧)