1. 打印View所有子视图
po [[self view]recursiveDescription]
2. layoutSubviews调用的调用时机
* 当视图第一次显示的时候会被调用 * 当这个视图显示到屏幕上了,点击按钮 * 添加子视图也会调用这个方法 * 当本视图的大小发生改变的时候是会调用的 * 当子视图的frame发生改变的时候是会调用的 * 当删除子视图的时候是会调用的
3. NSString过滤特殊字符
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
|
NSCharacterSet *set = [ NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\"" ];
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];
|
4. TransForm属性
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
|
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像素
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
首先在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. 计算方法耗时时间间隔
[Objective-C] 查看源文件 复制代码
1
2
3
|
#define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)
|
7. Color颜色宏定义
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
|
#define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]
#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提示宏定义
[Objective-C] 查看源文件 复制代码
1
|
#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show]
|
9. 让iOS应用直接退出
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
|
- ( 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 快速求总和 最大值 最小值 和 平均值
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
|
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);
|
10. 修改Label中不同文字颜色
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
|
- ( void )touchesEnded:( NSSet <UITouch> *)touches withEvent:(UIEvent *)event
{
[ self editStringColor: self .label.text editStr: @"好" color:[UIColor blueColor]];
}
- ( void )editStringColor:( NSString *)string editStr:( NSString *)editStr color:(UIColor *)color {
NSRange range = [string rangeOfString:editStr];
NSMutableAttributedString *attribute = [[ NSMutableAttributedString alloc] initWithString:string];
[attribute addAttributes:@{ NSForegroundColorAttributeName :color} range:range];
self .label.attributedText = attribute;
}
|
11. 播放声音
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
|
#import<AVFoundation>
NSString *path = [[ NSBundle mainBundle]pathForResource: @"pour_milk" ofType: @"wav" ];
NSURL *tempUrl = [ NSURL fileURLWithPath:path];
NSError *error = nil ;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self .player = play;
[play play];
|
12. 检测是否IPad Pro
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
7
8
9
|
- ( BOOL )isIpadPro
{
UIScreen *Screen = [UIScreen mainScreen];
CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;
BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
BOOL hasIPadProWidth = 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行间距
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
|
-( void )test{
NSMutableAttributedString *attributedString =
[[ NSMutableAttributedString alloc] initWithString: self .contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[ NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
[attributedString addAttribute: NSParagraphStyleAttributeName
value:paragraphStyle
range: NSMakeRange (0, [ self .contentLabel.text length])];
self .contentLabel.attributedText = attributedString;
}
|
26. UIImageView填充模式
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
|
@"UIViewContentModeScaleToFill" ,
@"UIViewContentModeScaleAspectFit" ,
@"UIViewContentModeScaleAspectFill" ,
@"UIViewContentModeRedraw" ,
@"UIViewContentModeCenter" ,
@"UIViewContentModeTop" ,
@"UIViewContentModeBottom" ,
@"UIViewContentModeLeft" ,
@"UIViewContentModeRight" ,
@"UIViewContentModeTopLeft" ,
@"UIViewContentModeTopRight" ,
@"UIViewContentModeBottomLeft" ,
@"UIViewContentModeBottomRight" ,
|
27. 宏定义检测block是否可用
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
7
|
#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); };
if (completionBlock) {
completionBlock(arg1, arg2);
}
BLOCK_EXEC(completionBlock, arg1, arg2);
|
28. Debug栏打印时自动把Unicode编码转化成汉字
[Objective-C] 查看源文件 复制代码
1
2
|
DXXcodeConsoleUnicodePlugin 插件
|
29. 设置状态栏文字样式颜色
[Objective-C] 查看源文件 复制代码
1
2
|
[[UIApplication sharedApplication] setStatusBarHidden: NO ];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
|
30. 自动生成模型代码的插件
31. iOS中的一些手势
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
|
轻击手势(TapGestureRecognizer)
轻扫手势(SwipeGestureRecognizer)
长按手势(LongPressGestureRecognizer)
拖动手势(PanGestureRecognizer)
捏合手势(PinchGestureRecognizer)
旋转手势(RotationGestureRecognizer)
|
32. iOS 开发中一些相关的路径
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
模拟器的位置:
/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 路径的方法
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
|
获取家目录路径的函数
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. 字符串相关操作
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
7
8
|
去除所有的空格
[str stringByReplacingOccurrencesOfString: @" " withString: @"" ]
去除首尾的空格
[str stringByTrimmingCharactersInSet:[ NSCharacterSet whitespaceCharacterSet]];
- ( NSString *)uppercaseString; 全部字符转为大写字母
- ( NSString *)lowercaseString 全部字符转为小写字母
|
35. CocoaPods pod install/pod update更新慢的问题
[Objective-C] 查看源文件 复制代码
1
2
3
|
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的参数,默认会升级CocoaPods的spec仓库,加一个参数可以省略这一步,然后速度就会提升不少。
|
36. MRC和ARC混编设置方式
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
|
在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线的位置
[Objective-C] 查看源文件 复制代码
1
|
tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
|
39. 设置滑动的时候隐藏navigationbar
[Objective-C] 查看源文件 复制代码
1
|
navigationController.hidesBarsOnSwipe = Yes
|
40. 自动处理键盘事件,实现输入框防遮挡的插件
IQKeyboardManager https://github.com/hackiftekhar/IQKeyboardManager
41. Quartz2D相关
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
图形上下是一个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. 屏幕截图
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
|
UIGraphicsBeginImageContextWithOptions( self .view.bounds.size, NO ,0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[ self .view.layer renderInContext:ctx];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(image, nil , nil , nil );
|
43. 隐藏导航栏上的返回字体
[Objective-C] 查看源文件 复制代码
1
2
3
4
|
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default)
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
|
44. 解决tableview的分割线短一截
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
|
-( 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
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
- ( 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这个量,在上滑和下滑时,变化极小(小数),但是因为方向不同,有正负之分,这就很好处理了。
(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: 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://7xstl7.com1.z0.glb.clouddn.com/%E6%8A%80%E6%9C%AF/nav_hide.gif)
46. 设置导航栏透明
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
|
[[[ self .navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:0.1];
- ( void )setNavigationBarColor:(UIColor *)color targetController:(UIViewController *)targetViewController{
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. 设置字体和行间距
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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];
NSRange blueRange = NSMakeRange ([[str string] rangeOfString: @"Frank_chun" ].location, [[str string] rangeOfString: @"Frank_chun" ].length);
[str addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange];
NSRange blueRange1 = NSMakeRange ([[str string] rangeOfString: @"438637472" ].location, [[str string] rangeOfString: @"438637472" ].length);
[str addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:blueRange1];
NSMutableParagraphStyle * par = [[ NSMutableParagraphStyle alloc]init];
[par setLineSpacing:20];
[str addAttribute: NSParagraphStyleAttributeName value:par range: NSMakeRange (0, lable.text.length)]; [lable setAttributedText:str];
|
效果图
![](http://7xstl7.com1.z0.glb.clouddn.com/%E6%8A%80%E6%9C%AF/learn.png)
48. 点击button倒计时
//第一种方法
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#import "ViewController.h"
@interface ViewController ()
@property ( nonatomic , strong) UIButton * timeButton;
@property ( nonatomic , strong) NSTimer * timer;
@property ( nonatomic , strong)UIButton * btn;
@end @implementation ViewController
{
NSInteger _time;
}
- ( void )viewDidLoad {
[ super viewDidLoad];
_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: self action: @selector (btnAction:) forControlEvents:UIControlEventTouchUpInside];
[ self refreshButtonWidth];
[ 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:[ self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];
[_btn setBackgroundImage:[ self imageWithColor:[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();
return image;
}
- ( void )btnAction:(UIButton *)sender{
sender.enabled = NO ;
[ self refreshButtonWidth];
[sender setTitle:[ NSString stringWithFormat: @"获取验证码(%zi)" , _time] forState:UIControlStateNormal];
_timer = [ NSTimer scheduledTimerWithTimeInterval:0.1 target: self selector: @selector (timeDown) userInfo: nil repeats: YES ];
}
- ( void )timeDown{
_time --;
if (_time == 0) {
[_btn setTitle: @"重新获取" forState:UIControlStateNormal]; _btn.enabled = YES ;
[ self refreshButtonWidth];
[_timer invalidate];
_timer = nil ;
_time = 5 ;
return ;
}
[_btn setTitle:[ NSString stringWithFormat: @"获取验证码(%zi)" , _time] forState:UIControlStateNormal];
}
|
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#pragma mark -点击发送验证码
- ( void )sendMessage:(UIButton *)btn{
if ( self .phoneField.text.length == 0) {
[ self remindMessage: @"请输入正确的手机号" ];
} else {
__block int timeout=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 {
int seconds = timeout % 60;
NSString *strTime = [ NSString stringWithFormat: @"%d" , seconds];
if ([strTime isEqualToString: @"0" ]) {
strTime = [ NSString stringWithFormat: @"%d" ,60];
}
dispatch_async(dispatch_get_main_queue(), ^{
[UIView beginAnimations: nil context: nil ];
[UIView setAnimationDuration:1];
[btn setTitle:[ NSString stringWithFormat: @"%@秒后重新发送" ,strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
btn.userInteractionEnabled = NO ;
});
timeout--;
}
});
dispatch_resume(_timer);
}
|
效果图
![](http://7xstl7.com1.z0.glb.clouddn.com/%E6%8A%80%E6%9C%AF/buton_timer.gif)
49. UITextField默认占位符是居中显示,让其居上显示
[Objective-C] 查看源文件 复制代码
1
|
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
|
50. 解决同时按两个按钮进两个view的问题
[button setExclusiveTouch:YES];
51. 图片拉伸
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
6
|
UIImage* img=[UIImage imageNamed: @"2.png" ];
UIEdgeInsets edge=UIEdgeInsetsMake(0, 10, 0,10);
img= [img resizableImageWithCapInsets:edge resizingMode:UIImageResizingModeStretch];
self .imageView.image=img;
|
52. 修改textFieldplaceholder字体颜色和大小
[Objective-C] 查看源文件 复制代码
1
2
|
textField.placeholder = @"username is in here!" ; [/p][textField setValue:[UIColor redColor] forKeyPath: @"_placeholderLabel.textColor" ];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath: @"_placeholderLabel.font" ];
|
53. 修改状态栏字体颜色
[Objective-C] 查看源文件 复制代码
1
2
3
4
|
只能设置两种颜色,黑色和白色,系统默认黑色
设置为白色方法:
(1)在plist里面添加Status bar style,值为UIStatusBarStyleLightContent(白色)或UIStatusBarStyleDefault(黑 色)
(2)在Info.plist中设置UIViewControllerBasedStatusBarAppearance 为 NO
|
54. 去掉导航栏下边的黑线
[Objective-C] 查看源文件 复制代码
1
2
|
[ self .navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self .navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
|
55. 修改pagecontrol颜色
[Objective-C] 查看源文件 复制代码
1
2
|
_pageControl.currentPageIndicatorTintColor=SFQRedColor;
_pageControl.pageIndicatorTintColor=SFQGrayColor;
|
56. 去掉UITableView的section的粘性,使其不会悬停
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
|
- ( 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);
} else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
|
57. 通过2D仿射函数实现小的动画效果(变大缩小) --可用于自定义pageControl中
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
|
[UIView animateWithDuration:0.3 animations:^{
imageView.transform = CGAffineTransformMakeScale(2, 2);
} completion:^( BOOL finished) {
imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
}];
|
58. UIImage与字符串互转
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
|
-( NSString *)UIImageToBase64Str:(UIImage *) image
{
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *encodedImageStr = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength ];
return encodedImageStr;
}
-(UIImage *)Base64StrToUIImage:( NSString *)_encodedImageStr
{
NSData *_decodedImageData = [[ NSData alloc] initWithBase64Encoding:_encodedImageStr];
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
return _decodedImage;
}
|
59. 判断NSString中是否包含中文
[Objective-C] 查看源文件 复制代码
1
2
3
4
5
|
-( BOOL )isChinese:( NSString *)str{
NSString *match= @"(^[\u4e00-\u9fa5]+$)" ;
NSPredicate *predicate = [ NSPredicate predicateWithFormat: @"SELF matches %@" , match];
return [predicate evaluateWithObject:str];
}
|
60. NSDate与NSString的相互转化
[Objective-C] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
-( NSString *)dateToString:( NSDate *)date {
NSDateFormatter *matter = [[ NSDateFormatter alloc] init];
[matter setDateFormat: @"yyyy-MM-dd hh:mm:ss zzz" ];
NSString *dateStr = [matter stringFromDate:date];
return dateStr;
}
-( NSDate *)stringToDate:( NSString *)dateStr {
NSDateFormatter *matter = [[ NSDateFormatter alloc] init];
[matter setDateFormat: @"yyyy-MM-dd hh:mm:ss zzz" ];
NSDate *date = [matter dateFromString:dateStr];
return date;
}
|
|