iOS 知识-常用小技巧大杂烩

1. 打印View所有子视图

po [[self view]recursiveDescription]

2. layoutSubviews调用的调用时机

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

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

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

* 当本视图的大小发生改变的时候是会调用的

* 当子视图的frame发生改变的时候是会调用的

* 当删除子视图的时候是会调用的

3. NSString过滤特殊字符

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

NSCharacterSet*set = [NSCharacterSetcharacterSetWithCharactersInString:

@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];

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

NSString*newString = [trimString stringByTrimmingCharactersInSet:set];

4. TransForm属性

//平移按钮

CGAffineTransform transForm =self.buttonView.transform;

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

//旋转按钮

CGAffineTransform transForm =self.buttonView.transform;

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(setSeparatorInset:)]) {

[self.tableView setSeparatorInset:UIEdgeInsetsZero];

}

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

[self.tableView setLayoutMargins:UIEdgeInsetsZero];

}

然后在重写willDisplayCell方法

- (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];

}

}

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提示宏定义


1#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:^(BOOLfinished) {

exit(0);

}];

}

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


NSArray*array = [NSArrayarrayWithObjects:@"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);

10. 修改Label中不同文字颜色

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

{

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

}

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

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

NSRangerange = [string rangeOfString:editStr];

NSMutableAttributedString*attribute = [[NSMutableAttributedStringalloc] initWithString:string];

// 设置属性修改字体颜色UIColor与大小UIFont

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

self.label.attributedText = attribute;

}

11. 播放声音


#import

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

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

//  2.将路劲转化为url

NSURL*tempUrl = [NSURLfileURLWithPath:path];

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

NSError*error =nil;

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

self.player = play;

//  4.播放

[play play];

12. 检测是否IPad Pro

- (BOOL)isIpadPro

{

UIScreen *Screen = [UIScreen mainScreen];

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

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

BOOLisIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;

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

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

下次重新运行项目,然后就不报错了。

25. Label行间距

-(void)test{

NSMutableAttributedString*attributedString =

[[NSMutableAttributedStringalloc] initWithString:self.contentLabel.text];

NSMutableParagraphStyle*paragraphStyle =  [[NSMutableParagraphStylealloc] init];

[paragraphStyle setLineSpacing:3];

//调整行间距

[attributedString addAttribute:NSParagraphStyleAttributeName

value:paragraphStyle

range:NSMakeRange(0, [self.contentLabel.text length])];

self.contentLabel.attributedText = attributedString;

}

26. UIImageView填充模式

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

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

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

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

@"UIViewContentModeCenter",// 中间

@"UIViewContentModeTop",// 顶部

@"UIViewContentModeBottom",// 底部

@"UIViewContentModeLeft",// 中间贴左

@"UIViewContentModeRight",// 中间贴右

@"UIViewContentModeTopLeft",// 贴左上

@"UIViewContentModeTopRight",// 贴右上

@"UIViewContentModeBottomLeft",// 贴左下

@"UIViewContentModeBottomRight",// 贴右下

27. 宏定义检测block是否可用

#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };

// 宏定义之前的用法

if(completionBlock)   {

completionBlock(arg1, arg2);

}

// 宏定义之后的用法

BLOCK_EXEC(completionBlock, arg1, arg2);

28. Debug栏打印时自动把Unicode编码转化成汉字

// 有时候我们在xcode中打印中文,会打印出Unicode编码,还需要自己去一些在线网站转换,有了插件就方便多了。

DXXcodeConsoleUnicodePlugin 插件

29. 设置状态栏文字样式颜色

[[UIApplication sharedApplication] setStatusBarHidden:NO];

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

30. 自动生成模型代码的插件

// 可自动生成模型的代码,省去写模型代码的时间

ESJsonFormat-for-Xcode

31. iOS中的一些手势

轻击手势(TapGestureRecognizer)

轻扫手势(SwipeGestureRecognizer)

长按手势(LongPressGestureRecognizer)

拖动手势(PanGestureRecognizer)

捏合手势(PinchGestureRecognizer)

旋转手势(RotationGestureRecognizer)

32. iOS 开发中一些相关的路径

模拟器的位置:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs

文档安装位置:

/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

插件保存路径:

~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins

自定义代码段的保存路径:

~/Library/Developer/Xcode/UserData/CodeSnippets/

如果找不到CodeSnippets文件夹,可以自己新建一个CodeSnippets文件夹。

证书路径

~/Library/MobileDevice/Provisioning Profiles

33. 获取 iOS 路径的方法


获取家目录路径的函数

NSString*homeDir =NSHomeDirectory();

获取Documents目录路径的方法

NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString*docDir = [paths objectAtIndex:0];

获取Documents目录路径的方法

NSArray*paths =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);

NSString*cachesDir = [paths objectAtIndex:0];

获取tmp目录路径的方法:

NSString*tmpDir =NSTemporaryDirectory();

34. 字符串相关操作

去除所有的空格

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

去除首尾的空格

[str stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];

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

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

35. CocoaPods pod install/pod update更新慢的问题


pod install --verbose --no-repo-update

pod update --verbose --no-repo-update

如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。

36. MRC和ARC混编设置方式

在XCode中targets的build phases选项下Compile Sources下选择 不需要arc编译的文件

双击输入 -fno-objc-arc 即可

MRC工程中也可以使用ARC的类,方法如下:

在XCode中targets的build phases选项下Compile Sources下选择要使用arc编译的文件

双击输入 -fobjc-arc 即可

37. 把tableview里cell的小对勾的颜色改成别的颜色

[Objective-C]查看源文件复制代码

?

1_mTableView.tintColor = [UIColor redColor];

38. 调整tableview的separaLine线的位置

1tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

39. 设置滑动的时候隐藏navigationbar


1navigationController.hidesBarsOnSwipe = Yes

40. 自动处理键盘事件,实现输入框防遮挡的插件

IQKeyboardManager

https://github.com/hackiftekhar/IQKeyboardManager

41. Quartz2D相关


图形上下是一个CGContextRef类型的数据。

图形上下文包含:

1,绘图路径(各种各样图形)

2,绘图状态(颜色,线宽,样式,旋转,缩放,平移)

3,输出目标(绘制到什么地方去?UIView、图片)

1,获取当前图形上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

2,添加线条

CGContextMoveToPoint(ctx, 20, 20);

3,渲染

CGContextStrokePath(ctx);

CGContextFillPath(ctx);

4,关闭路径

CGContextClosePath(ctx);

5,画矩形

CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120));

6,设置线条颜色

[[UIColor redColor] setStroke];

7, 设置线条宽度

CGContextSetLineWidth(ctx, 20);

8,设置头尾样式

CGContextSetLineCap(ctx, kCGLineCapSquare);

9,设置转折点样式

CGContextSetLineJoin(ctx, kCGLineJoinBevel);

10,画圆

CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100));

11,指定圆心

CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1);

12,获取图片上下文

UIGraphicsGetImageFromCurrentImageContext();

13,保存图形上下文

CGContextSaveGState(ctx)

14,恢复图形上下文

CGContextRestoreGState(ctx)

42. 屏幕截图

// 1. 开启一个与图片相关的图形上下文

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

// 2. 获取当前图形上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

// 3. 获取需要截取的view的layer

[self.view.layer renderInContext:ctx];

// 4. 从当前上下文中获取图片

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

// 5. 关闭图形上下文

UIGraphicsEndImageContext();

// 6. 把图片保存到相册

UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);

43. 隐藏导航栏上的返回字体

//Swift

UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)

//OC

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

44. 解决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];

}

}

45. 动态隐藏NavigationBar


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

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

{

if(velocity.y > 0)

{

[self.navigationController setNavigationBarHidden:YESanimated:YES];

}else{

[self.navigationController setNavigationBarHidden:NOanimated:YES];

}

}

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

//2.在滑动过程中隐藏

//像safari

(1)

self.navigationController.hidesBarsOnSwipe =YES;

(2)

- (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:NOanimated:YES];

}else{

//上滑趋势,隐藏

[self.navigationController setNavigationBarHidden:YESanimated:YES];

}

}else{

[self.navigationController setNavigationBarHidden:NOanimated:YES];

}

}

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

效果图

46. 设置导航栏透明

//方法一:设置透明度

[[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1];

//方法二:设置背景图片

/**

* 设置导航栏,使其透明

*

*/

- (void)setNavigationBarColor:(UIColor *)color targetController:(UIViewController *)targetViewController{

//导航条的颜色 以及隐藏导航条的颜色targetViewController.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];

CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect);

UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [targetViewController.navigationController.navigationBar setBackgroundImage:theImage forBarMetrics:UIBarMetricsDefault];

}

47. 设置字体和行间距

//设置字体和行间距

UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 300, 200)];

lable.text =@"大家好,我是Frank_chun,在这里我们一起学习新的知识,总结我们遇到的那些坑,共同的学习,共同的进步,共同的努力,只为美好的明天!!!有问题一起相互的探讨--438637472!!!";

lable.numberOfLines = 0;

lable.font = [UIFont systemFontOfSize:12];

lable.backgroundColor = [UIColor grayColor];

[self.view addSubview:lable];

//设置每个字体之间的间距

//NSKernAttributeName 这个对象所对应的值是一个NSNumber对象(包含小数),作用是修改默认字体之间的距离调整,值为0的话表示字距调整是禁用的; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:lable.text attributes:@{NSKernAttributeName:@(5.0)}];

//设置某写字体的颜色

//NSForegroundColorAttributeName 设置字体颜色

NSRangeblueRange =NSMakeRange([[str string] rangeOfString:@"Frank_chun"].location, [[str string] rangeOfString:@"Frank_chun"].length);

[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:blueRange];

NSRangeblueRange1 =NSMakeRange([[str string] rangeOfString:@"438637472"].location, [[str string] rangeOfString:@"438637472"].length);

[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:blueRange1];

//设置每行之间的间距

//NSParagraphStyleAttributeName 设置段落的样式

NSMutableParagraphStyle* par = [[NSMutableParagraphStylealloc]init];

[par setLineSpacing:20];

//为某一范围内文字添加某个属性

//NSMakeRange表示所要的范围,从0到整个文本的长度

[str addAttribute:NSParagraphStyleAttributeNamevalue:par range:NSMakeRange(0, lable.text.length)]; [lable setAttributedText:str];

效果图

48. 点击button倒计时

//第一种方法


//第一种方法

//点击button倒计时

#import "ViewController.h"

@interfaceViewController ()

@property(nonatomic, strong) UIButton * timeButton;

@property(nonatomic, strong)NSTimer* timer;

@property(nonatomic, strong)UIButton * btn;

@end@implementationViewController

{

NSInteger_time;

}

- (void)viewDidLoad {

[superviewDidLoad];

_time = 5;

self.btn = [UIButton buttonWithType:UIButtonTypeCustom]; _btn.backgroundColor = [UIColor orangeColor];

[_btn setTitle:@"获取验证码"forState:UIControlStateNormal]; _btn.titleLabel.font = [UIFont systemFontOfSize:15];

[_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[_btn addTarget:selfaction:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];

[selfrefreshButtonWidth];

[self.view addSubview:self.btn];

}

- (void)refreshButtonWidth{

CGFloat width = 0;

if(_btn.enabled){

width = 100;

}else{

width = 200;

}

_btn.center = CGPointMake(self.view.frame.size.width/2, 200);

_btn.bounds = CGRectMake(0, 0, width, 40);

//每次刷新,保证区域正确

[_btn setBackgroundImage:[selfimageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];

[_btn setBackgroundImage:[selfimageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled];

}

- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize{

CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height); UIGraphicsBeginImageContext(rect.size);

CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();

returnimage;

}

- (void)btnAction:(UIButton *)sender{

sender.enabled =NO;

[selfrefreshButtonWidth];

[sender setTitle:[NSStringstringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal];

_timer = [NSTimerscheduledTimerWithTimeInterval:0.1 target:selfselector:@selector(timeDown) userInfo:nilrepeats:YES];

}

- (void)timeDown{

_time --;

if(_time == 0) {

[_btn setTitle:@"重新获取"forState:UIControlStateNormal]; _btn.enabled =YES;

[selfrefreshButtonWidth];

[_timer invalidate];

_timer =nil;

_time = 5 ;

return;

}

[_btn setTitle:[NSStringstringWithFormat:@"获取验证码(%zi)", _time] forState:UIControlStateNormal];

}


//第二种方法

#pragma mark -点击发送验证码

- (void)sendMessage:(UIButton *)btn{

if(self.phoneField.text.length == 0) {

[selfremindMessage:@"请输入正确的手机号"];

}else{

__blockinttimeout=60;

//倒计时时间

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = 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, ^{

if(timeout<=0){

//倒计时结束,关闭

dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{

// 设置界面的按钮显示 根据自己需求设置

[btn setTitle:@"发送验证码"forState:UIControlStateNormal]; btn.userInteractionEnabled =YES;

});

}else{

intseconds = timeout % 60;

NSString*strTime = [NSStringstringWithFormat:@"%d", seconds];

if([strTime isEqualToString:@"0"]) {

strTime = [NSStringstringWithFormat:@"%d",60];

}

dispatch_async(dispatch_get_main_queue(), ^{

//设置界面的按钮显示 根据自己需求设置

//NSLog(@"____%@",strTime);

[UIView beginAnimations:nilcontext:nil];

[UIView setAnimationDuration:1];

[btn setTitle:[NSStringstringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];

[UIView commitAnimations];

btn.userInteractionEnabled =NO;

});

timeout--;

}

});

dispatch_resume(_timer);

}

效果图

49. UITextField默认占位符是居中显示,让其居上显示

[Objective-C]查看源文件复制代码

?

1textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;

50. 解决同时按两个按钮进两个view的问题

[button setExclusiveTouch:YES];

51. 图片拉伸

UIImage* img=[UIImage imageNamed:@"2.png"];//原图

UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10);

//UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片

//UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图

img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch];

self.imageView.image=img;

52. 修改textFieldplaceholder字体颜色和大小

textField.placeholder =@"username is in here!"; [/p][textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

53. 修改状态栏字体颜色


只能设置两种颜色,黑色和白色,系统默认黑色

设置为白色方法:

(1)在plist里面添加Status bar style,值为UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)

(2)在Info.plist中设置UIViewControllerBasedStatusBarAppearance 为NO

54. 去掉导航栏下边的黑线


[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];

self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];

55. 修改pagecontrol颜色

2

_pageControl.currentPageIndicatorTintColor=SFQRedColor;

_pageControl.pageIndicatorTintColor=SFQGrayColor;

56. 去掉UITableView的section的粘性,使其不会悬停

//有时候使用UITableView所实现的列表,会使用到section,但是又不希望它粘在最顶上而是跟随滚动而消失或者出现

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

if(scrollView == _tableView) {

CGFloat sectionHeaderHeight = 36;

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

}

}

}

57. 通过2D仿射函数实现小的动画效果(变大缩小) --可用于自定义pageControl中


[UIView animateWithDuration:0.3 animations:^{

imageView.transform = CGAffineTransformMakeScale(2, 2);

} completion:^(BOOLfinished) {

imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);

}];

58. UIImage与字符串互转

//图片转字符串

-(NSString*)UIImageToBase64Str:(UIImage *) image

{

NSData*data = UIImageJPEGRepresentation(image, 1.0f);

NSString*encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

returnencodedImageStr;

}

//字符串转图片

-(UIImage *)Base64StrToUIImage:(NSString*)_encodedImageStr

{

NSData*_decodedImageData   = [[NSDataalloc] initWithBase64Encoding:_encodedImageStr];

UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];

return_decodedImage;

}

59. 判断NSString中是否包含中文


-(BOOL)isChinese:(NSString*)str{

NSString*match=@"(^[\u4e00-\u9fa5]+$)";

NSPredicate*predicate = [NSPredicatepredicateWithFormat:@"SELF matches %@", match];

return[predicate evaluateWithObject:str];

}

60. NSDate与NSString的相互转化

-(NSString*)dateToString:(NSDate*)date {

// 初始化时间格式控制器

NSDateFormatter*matter = [[NSDateFormatteralloc] init];

// 设置设计格式

[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];

// 进行转换

NSString*dateStr = [matter stringFromDate:date];

returndateStr;

}

-(NSDate*)stringToDate:(NSString*)dateStr {

// 初始化时间格式控制器

NSDateFormatter*matter = [[NSDateFormatteralloc] init];

// 设置设计格式

[matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];

// 进行转换

NSDate*date = [matter dateFromString:dateStr];

returndate;

}

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

推荐阅读更多精彩内容

  • 获取磁盘总空间大小 //磁盘总空间 (CGFloat)diskOfAllSizeMBytes{CGFloat si...
    UILabelkell阅读 1,269评论 0 2
  • 打印View所有子视图 layoutSubviews调用的调用时机 当视图第一次显示的时候会被调用当这个视图显示到...
    hyeeyh阅读 463评论 0 3
  • 一.观察者模式介绍 观察者模式是一个使用率非常高的模式,它最常用的地方是GUI系统,订阅-发布系统。因为这个模式的...
    Android开发知识总结阅读 1,114评论 8 6
  • 昨晚我又梦见你了,还是和以往一样,没敢和你讲话,怕被你发现。 梦里绿荫道两旁超大的树,当然如果用电线杆子来行容那是...
    静言思之lqr阅读 85评论 0 0
  • 谈恋爱就应该经历一下异地恋,体会一下欣喜忧愁无从分享,欢笑落泪不能拥抱,隔着屏幕隔着电话隔着书信联系直到你几乎发疯...
    阿花呀_阅读 126评论 0 1