路径解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIImage *image = [UIImage imageNamed:@""];
// 使用`imageNamed:`初始化的时候,会先检查缓存中是否存在要加载的照片,如不存在,图片首先会被缓存起来,然后才返回要加载的图片对象;如果存在,直接返回要加载的照片对象。

NSString *path = [[NSBundle mainBundle]pathForResource:@"1.png" ofType:nil];
NSLog(@"%@",path);
UIImage *image2 = [UIImage imageWithContentsOfFile:path];
// 使用`imageWithContentsOfFile:`创建图片的时候,是直接从磁盘上加载。当收到内存警告时,图片对象会被释放,下一次绘图的时候,需要重新加载。

NSData *data;
UIImage *image3 = [UIImage imageWithData:data];
// data 是照片数据,一般是请求返回的,然后通过`imageWithData:`创建图片。
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

沙盒路径

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// 数据是写在Library->Preferences下
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
NSLog(@"%p",defaults1);
NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
NSLog(@"%p",defaults2);

NSUserDefaults *defaults3 = [[NSUserDefaults alloc]init];
NSLog(@"%p",defaults3);

NSArray *tempArray = @[@"1",@"2"];
[defaults1 setObject:tempArray forKey:@"array"];

// 1、获取程序的Home目录
// NSString *homeDirectory = NSHomeDirectory();
// NSLog(@"path:%@", homeDirectory);

// 2、获取document目录
// NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentPath = [documentPaths objectAtIndex:0];
// NSLog(@"path:%@", documentPath);

// 3、获取Cache目录
// NSArray *CachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
// NSString *CachePath = [CachePaths objectAtIndex:0];
// NSLog(@"%@", CachePath);

// 4、获取Library目录
// NSArray *LibraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
// NSString *LibraryPath = [LibraryPaths objectAtIndex:0];
// NSLog(@"%@", LibraryPath);

// 5、获取Tmp目录
// NSString *tmpDir = NSTemporaryDirectory();
// NSLog(@"%@", tmpDir);

// 6、写入文件
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *docDir = [paths objectAtIndex:0];
// NSLog(@"%@",docDir);
// if (!docDir) {
// NSLog(@"Documents 目录未找到");
// }
// NSArray *contentArray = [[NSArray alloc] initWithObjects:@"内容",@"content",nil];
// NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
// [contentArray writeToFile:filePath atomically:YES];


// 7、读取文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
NSLog(@"%@",filePath);
NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
NSLog(@"%@", array);


// 8、判断一个文件是否存在,传入全路径(fileExistsAtPath)
// // 创建文件管理器
// NSFileManager * fileManager = [NSFileManager defaultManager];
//
// NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// NSString * filePath = [documents stringByAppendingPathComponent:@"test"];
//
// // 判断一个文件是否存在,传入全路径
// if ([fileManager fileExistsAtPath:filePath]) {
// NSLog(@"it is exit");
// }


// 9、在Documents里创建目录
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSLog(@"documentsDirectory%@",documentsDirectory);
// NSFileManager *fileManager = [NSFileManager defaultManager];
// NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// // 创建目录
// [fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];


// 10、在目录下创建文件
// NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];
// NSString *testPath2 = [testDirectory stringByAppendingPathComponent:@"test22.txt"];
// NSString *testPath3 = [testDirectory stringByAppendingPathComponent:@"test33.txt"];
// NSString *string = @"写入内容,write String";
// [fileManager createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
// [fileManager createFileAtPath:testPath2 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
// [fileManager createFileAtPath:testPath3 contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];


// 11、获取目录列里所有文件名
// 两种方法获取:subpathsOfDirectoryAtPath 和subpathsAtPath
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// NSLog(@"documentsDirectory%@",documentsDirectory);
// NSFileManager *fileManage = [NSFileManager defaultManager];
// NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];
// NSLog(@"%@",file);
// NSArray *files = [fileManage subpathsAtPath: myDirectory ];
// NSLog(@"%@",files);


// 12、fileManager使用操作当前目录
// //创建文件管理器
// NSFileManager *fileManager = [NSFileManager defaultManager];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *documentsDirectory = [paths objectAtIndex:0];
// //更改到待操作的目录下
// [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
// //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil
// NSString * fileName = @"testFileNSFileManager.txt";
// NSArray *array = [[NSArray alloc] initWithObjects:@"hello world",@"hello world1", @"hello world2",nil];
// [fileManager createFileAtPath:fileName contents:array attributes:nil];

// 13、删除文件
// [fileManager removeItemAtPath:fileName error:nil];

}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

UIAlertController

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

for (int i = 0 ; i < 2; i ++) {
UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(120 + i * 120, 120, 100, 50);
button.backgroundColor = [UIColor lightGrayColor];
if (i == 0) {
[button setTitle:@"alertView" forState:UIControlStateNormal];
}else{
[button setTitle:@"actionSheet" forState:UIControlStateNormal];
}
button.tag = 10 + i ;
[button addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];
}

}
-(void)onClick:(UIButton*)button{

if (button.tag == 10) {
NSLog(@"alertView");
[self alertView];
}else{
NSLog(@"actionSheet");
[self actionSheet];
}
}
-(void)actionSheet{
// 初始化UIAlertCOntroller
// Title:标题
// message:信息
// Style:样式
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];

// 初始化UIAlertAction
UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];

UIAlertAction *firstBtn = [UIAlertAction actionWithTitle:@"first" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];



[alertController addAction:cancelBtn];
[alertController addAction:firstBtn];
[self presentViewController:alertController animated:YES completion:nil];

}
-(void)alertView{
// 初始化UIAlertController
// Title:标题
// message:信息
// Style:样式
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
// UIAlertControllerStyleActionSheet
// UIAlertControllerStyleAlert

// 初始化按钮
// Title:标题
// style:样式
// UIAlertController 上面只能有一个取消样式的按钮,否则会崩溃
UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
NSLog(@"取消");
}];
// UIAlertActionStyleDefault = 0,普通按钮
// UIAlertActionStyleCancel,取消按钮
// UIAlertActionStyleDestructive重置、销毁

// 添加文本输入框
[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"请输入";
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField * textField) {
textField.placeholder = @"第二个文本输入框";
}];

UIAlertAction *resetBtn = [UIAlertAction actionWithTitle:@"reset" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {

UITextField *textField1 = alertController.textFields[0];
NSLog(@"%@",textField1.text);

UITextField *textField2 = alertController.textFields[1];
NSLog(@"%@",textField2.text);
}];


// 添加动作
[alertController addAction:cancelBtn];
[alertController addAction:resetBtn];


// 模态
[self presentViewController:alertController animated:YES completion:nil];
}
@end

UIActivityIndicatorView

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#import "myButton.h"

@implementation myButton

+(UIButton *)buttonWithFrame:(CGRect)frame BGColor:(UIColor *)color Title:(NSString *)title NormalImage:(UIImage *)normalImage Tag:(int)tag Method:(SEL)method Object:(id)object{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = frame;
button.backgroundColor = color;
[button setTitle:title forState:UIControlStateNormal];
button.tag = tag;
[button setBackgroundImage:normalImage forState:UIControlStateNormal];
[button addTarget:object action:method forControlEvents:UIControlEventTouchUpInside];
return button;
}

@end


#import "ViewController.h"
#import "myButton.h"
@interface ViewController ()
{
UIActivityIndicatorView *act;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];


[self createBtn];
[self createActivityIndicatorView];
}
-(void)onClick:(UIButton*)button{
if (act.isAnimating == YES) {
[act stopAnimating];
}else if(act.isAnimating == NO){
[act startAnimating];
}

}
-(void)createActivityIndicatorView{

// UIActivityIndicatorViewStyleWhiteLarge,大白
// UIActivityIndicatorViewStyleWhite,白色
// UIActivityIndicatorViewStyleGray 灰色
// 初始化并设置样式
act = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
act.frame = CGRectMake(100, 300, 50, 50);
// 设置中心点为屏幕中心点
act.center = self.view.center;
[self.view addSubview:act];

act.backgroundColor = [UIColor redColor];

// 设置变大4倍
act.transform = CGAffineTransformMakeScale(4, 4);

act.tag = 10;
// 停止时是否隐藏,默认是YES
act.hidesWhenStopped = YES;
}
-(void)createBtn{
UIButton *startBtn = [myButton buttonWithFrame:CGRectMake(100, 100, 50, 50) BGColor:[UIColor lightGrayColor] Title:@"开始" NormalImage:nil Tag:10 Method:@selector(onClick:) Object:self];

[self.view addSubview:startBtn];

UIButton *endBtn = [myButton buttonWithFrame:CGRectMake(180, 100, 50, 50) BGColor:[UIColor lightGrayColor] Title:@"停止" NormalImage:nil Tag:11 Method:@selector(onClick:) Object:self];
[self.view addSubview:endBtn];

[self.view setBackgroundColor:[UIColor yellowColor]];
}
@end

路径解析

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#import "FyQuestion.h"

@implementation FyQuestion

// 判断是绝对路径: 以 /开头的就是绝对路径
// -->./ios/day1/
// -->/oc/day
- (BOOL)isAbsolutePath:(NSString *)path {
//直接利用判断开头的这样的方法 harPrefix
return [path hasPrefix:@"/"];
}

// 取得路径path最后的部分 /home/xuanmac ---> xuanmac, /home/xuanmac/1.txt--->1.txt
- (NSString *)lastPathComponent:(NSString *)path {
//第一步,判断是否末尾存在/
int flag = 0;
NSString * subStr = nil;
if ([path hasSuffix:@"/"]) {
//截取字符方法,subStringToIndex
subStr = [path substringToIndex:[path length] - 1];
flag = 1;
}

//利用查找字符串方法,option 是倒序查找
//查找方法,返回的是一个范围
NSRange range = {0,0};
if (flag) {
//NSBackwardsSearch 倒序查找的指令
range = [subStr rangeOfString:@"/" options:NSBackwardsSearch];
//substringFromIndex 从指定位置到字符串结尾,包括指定位置
return [subStr substringFromIndex:range.location + 1];
} else {
range = [path rangeOfString:@"/" options:NSBackwardsSearch];
return [path substringFromIndex:range.location + 1];
}
}

// 删除路径path最后的部分 /home/xuanmac/ ---> /home, /home/xuanmac/1.txt--->/home/xuanmac
- (NSString *)stringByDeletingLastPathComponent:(NSString *)path {

NSString * subStr = nil;
//判断path末尾是不是以/结尾
if ([path hasSuffix:@"/"]) {
subStr = [path substringToIndex:path.length - 1];
} else {
subStr = path;
}

//倒序查找
NSRange range = [subStr rangeOfString:@"/" options:NSBackwardsSearch];

NSString * str = [subStr substringToIndex:range.location];

return [NSString stringWithString:str];

}
// 在路径上追加路径/home/xuanmac/ 和 demo/abc-->/home/xuanmac/demo/abc
- (NSString *)stringByAppendingPathComponent:(NSString *)path withPath:(NSString *)subPath {
NSMutableString * mStr = [NSMutableString stringWithString:path];
//判断是否是以/结尾
if ([mStr hasSuffix:@"/"]) {
if ([subPath hasPrefix:@"/"]) {
[mStr appendString:[subPath substringFromIndex:1]];
} else {
[mStr appendString:subPath];
}

} else {
if ([subPath hasPrefix:@"/"]) {
[mStr appendFormat:@"/%@",[subPath substringFromIndex:1]];
} else {
[mStr appendFormat:@"/%@",subPath];
}
}

return [NSString stringWithString:mStr];
}

// 取得文件的扩展名/home/xuanmac/1.txt --> txt
- (NSString *)pathExtension:(NSString *)path {
#if 1
//pathExtension 获取路径拓展名
NSString * str = path.pathExtension;
return [NSString stringWithString:str];
#else
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];
NSString * str = [path substringFromIndex:range.location + 1];
return [NSString stringWithString:str];
#endif
}

// 删除文件扩展名/home/xuanmac/1.txt --> /home/xuanmac/1
- (NSString *)stringByDeletingPathExtension:(NSString *)path {
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];

NSString * str = [path substringToIndex:range.location];
return [NSString stringWithString:str];
}
// 去除里面多余的 /路径 Duplicate重复 Slash表示斜线
// path = @"///home//xuanmac/ios/oc/day1/"; 返回@"/home/xuanmac/ios/oc/day1"
- (NSString *) removeDuplicateSlash:(NSString *)path {
#if 1
//看到//我们就要处理掉一个,知道在path没有// NSNotFound
//path 转换成可变字符串
NSMutableString * mStr = [NSMutableString stringWithString:path];

while (1) {
NSRange range = [mStr rangeOfString:@"//"];
//判断是否还存在,如果不存在@"//",跳出循环
if (NSNotFound == range.location) {
break;
}
//每次都删除//当中的一个
[mStr deleteCharactersInRange:NSMakeRange(range.location, 1)];
}

//处理完//之后,我们要处理路径末尾的/
if([mStr hasSuffix:@"/"])
{
[mStr deleteCharactersInRange:NSMakeRange(mStr.length - 1, 1)];
}

return [NSString stringWithString:mStr];
#else
NSArray * array = [path componentsSeparatedByString:@"/"];
NSMutableArray * mArray = [NSMutableArray arrayWithArray:array];
[mArray removeObject:@""];

return [mArray componentsJoinedByString:@"/"];//?????
#endif
}
//-获取路径中的所有目录名---->/home/xuanmac/ios/oc --->home xuanmac ios oc
- (NSArray *)pathComponents:(NSString*)path {
return [path componentsSeparatedByString:@"/"];
}

+ (void)test {
FyQuestion * test = [[FyQuestion alloc] init];
NSLog(@"第一题");
NSLog(@"%hhd",[test isAbsolutePath:@"./ios/day1/"]);
NSLog(@"%hhd",[test isAbsolutePath:@"/ios/day1/"]);

NSLog(@"第二题");
NSString * str1 = [test lastPathComponent:@"/ios/day1/"];
NSLog(@"%@",str1);
NSString * str2 = [test lastPathComponent:@"/ios/day1/1.txt"];
NSLog(@"%@",str2);

NSLog(@"第三题");
NSString * str3 = [test stringByDeletingLastPathComponent:@"/ios/day1/"];
NSLog(@"%@",str3);
NSString * str4 = [test stringByDeletingLastPathComponent:@"/ios/day1/1.txt"];
NSLog(@"%@",str4);

NSLog(@"第四题");
NSString * str5 = [test stringByAppendingPathComponent:@"/ios/day1/" withPath:@"1.txt"];
NSLog(@"%@",str5);
NSString * str6 = [test stringByAppendingPathComponent:@"/ios/day1" withPath:@"/test/1.txt"];
NSLog(@"%@",str6);

NSLog(@"第五题");
NSLog(@"%@",[test pathExtension:@"/test/1.txt"]);

NSLog(@"第六题");
NSLog(@"%@",[test stringByDeletingPathExtension:@"/test/1.txt"]);
NSLog(@"第七题");
NSLog(@"%@",[test removeDuplicateSlash:@"/////////fdjkasj//fdhk///fdjsalfkjs///"]);
NSLog(@"第八题");

NSLog(@"第备用题");
}


@end
1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#import "RootViewController.h"

@interface RootViewController ()<UITextFieldDelegate>

@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self createTextField];
}
//创建UITextField
-(void)createTextField{
// 初始化UITextField
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 400, 180, 50)];
// 设置背景色
textField.backgroundColor = [UIColor yellowColor];
// 设置边框样式
textField.borderStyle = UITextBorderStyleRoundedRect;


// 一键清除butotn
textField.clearButtonMode = UITextFieldViewModeWhileEditing;

textField.delegate = self;

// 添加到视图
[self.view addSubview:textField];
}
#pragma mark - delegate

//点击return键,执行的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(@"点击了return");
// 注销第一响应
[textField resignFirstResponder];
return YES;
}

//是否能进入编辑
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
NSLog(@"将要开始编辑");
// YES:可以进入编辑
// NO:不能进入编辑
return YES;
}
//当上面的方法返回YES的时候,才会调用此代理方法
-(void)textFieldDidBeginEditing:(UITextField *)textField{
NSLog(@"已经开始编辑");
}
//将要结束编辑
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
NSLog(@"将要结束编辑");
// YES:可以结束编辑
// NO:不能结束编辑
return YES;
}
//当上面的方法返回YES的时候,才会调用此代理方法
//已经结束编辑
-(void)textFieldDidEndEditing:(UITextField *)textField{
NSLog(@"已经结束编辑");
}

//点击clearButton时调用的方法
-(BOOL)textFieldShouldClear:(UITextField *)textField{
// 当textField.text值是1的时候,不允许删除
if ([textField.text isEqualToString:@"1"]) {
return NO;
}
// YES:允许删除
// NO:不允许删除
return YES;
}

//获得每一次输入的字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

// NSLog(@"string = %@",string);

// 根据每次输入的字符,组成一个字符串
NSMutableString *mutableString = [[NSMutableString alloc]initWithString:textField.text];
[mutableString insertString:string atIndex:range.location];
NSLog(@"%@",mutableString);

return YES;
}
@end

View切换层级

1
2
3
4
5
6
7
8
9
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
#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self createSubViews];

}

-(void)createSubViews{

UILabel *redLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 100)];
redLabel.backgroundColor = [UIColor redColor];
redLabel.text = @"红色";
[self.view addSubview:redLabel];

UILabel *greenLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
greenLabel.backgroundColor = [UIColor greenColor];
greenLabel.text = @"绿色";
[self.view addSubview:greenLabel];

UILabel *blueLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 80, 100, 100)];
blueLabel.backgroundColor = [UIColor blueColor];
blueLabel.text = @"蓝色";
[self.view addSubview:blueLabel];

// 把子视图提到最前面
// [self.view bringSubviewToFront:redLabel];

// 把子视图放到最底层
// [self.view sendSubviewToBack:blueLabel];

// 把某一个子视图放到第0层
// [self.view insertSubview:blueLabel atIndex:0];

// 把blueLabel 放到greenLabel 下面
// [self.view insertSubview:blueLabel belowSubview:greenLabel];

// 把blueLabel放置到redLabel 上面
// [self.view insertSubview:redLabel aboveSubview:blueLabel];

NSLog(@"subViews = %@",self.view.subviews);

}

@end

键盘状态监听

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#import "RootViewController.h"

@interface RootViewController ()<UITextFieldDelegate>

@end

@implementation RootViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
myView.backgroundColor = [UIColor blackColor];
[self.view addSubview:myView];


[self.view setBackgroundColor:[UIColor redColor]];

[self createTextField];
}
-(void)createTextField{
// 初始化UITextField并设置frame
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 400, 100, 50)];
// 设置背景色
textField.backgroundColor = [UIColor yellowColor];

textField.delegate = self;

// 添加到视图
[self.view addSubview:textField];


// 键盘状态改变的时候,会发出以下通知
// UIKeyboardWillShowNotification; 键盘即将显示
// UIKeyboardDidShowNotification; 键盘显示完毕
// UIKeyboardWillHideNotification; 键盘即将消失
// UIKeyboardDidHideNotification;键盘消失完毕
// UIKeyboardWillChangeFrameNotification 键盘即将改变frame
// UIKeyboardDidChangeFrameNotification 键盘已经改变frame

// 获取通知中心
NSNotificationCenter*center = [NSNotificationCenter defaultCenter];

// 监听键盘弹出通知
[center addObserver:self selector:@selector(KeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// 监听键盘收起通知
[center addObserver:self selector:@selector(KeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

// 成为第一响应者
// [textField becomeFirstResponder];
}

//键盘将要消失时
-(void)KeyboardWillHide:(NSNotification*)noti{
NSLog(@"%@",noti.userInfo);
// UIKeyboardAnimationDurationUserInfoKey = "0.25";
// UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
// UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
// UIKeyboardFrameEndUserInfoKey = "NSRect: {{0,667}, {375, 258}}";


self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
//键盘将要出现
-(void)KeyboardWillShow:(NSNotification*)noti{
NSLog(@"%@",noti.userInfo);
// UIKeyboardAnimationDurationUserInfoKey = "0.25";
// UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
// UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
// UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
// UIKeyboardIsLocalUserInfoKey = 1;

CGRect rect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
NSLog(@"rect = %@",NSStringFromCGRect(rect));


self.view.frame = CGRectMake(0, -rect.size.height, self.view.frame.size.width, self.view.frame.size.height);
}

#pragma mark - textField delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
// 取消第一响应者
[textField resignFirstResponder];
return YES;
}
@end

手机晃动事件

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
#define screenWidth self.view.frame.size.width
#define screenHeight self.view.frame.size.height


#import "ViewController.h"

@interface ViewController ()
{
UIImageView *_topImageView;
UIImageView *_bottomImageView;
UIImageView *_showImageView;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self createImageViews];
}
//检测到手机晃动
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
// 显示中间的图片
[self showImageView];
NSLog(@"晃动开始");
}
//晃动结束
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
// 隐藏中间的图片
[self hideImageView];
NSLog(@"晃动结束");
}

-(void)hideImageView{
[UIView animateWithDuration:2 animations:^{
// 设置返回原始位置
_topImageView.frame = CGRectMake(0, 0, screenWidth, screenHeight/2);
_bottomImageView.frame = CGRectMake(0, screenHeight/2, screenWidth, screenHeight/2);
}];
}
-(void)showImageView{
// 使用动画为了更美观
[UIView animateWithDuration:1 animations:^{

_topImageView.frame = CGRectMake(0, -100, screenWidth, screenHeight/2);
_bottomImageView.frame = CGRectMake(0, screenHeight/2 + 100, screenWidth, screenHeight/2);
}];
}
#pragma mark 创建UI
-(void)createImageViews{

_showImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 150, 150)];
_showImageView.center = self.view.center;
_showImageView.image = [UIImage imageNamed:@"ShakeHideImg_women"];
[self.view addSubview:_showImageView];


_topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/2)];
_topImageView.image = [UIImage imageNamed:@"Shake_Logo_Up"];
[self.view addSubview:_topImageView];

_bottomImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, self.view.frame.size.height/2)];
_bottomImageView.image = [UIImage imageNamed:@"Shake_Logo_Down"];
[self.view addSubview:_bottomImageView];
}


@end

OC画图

1
2
3
4
5
6
7
8
9
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#import "Customview.h"

@implementation Customview
{
NSMutableArray *lineArray;
}

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor whiteColor]];

UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"撤销" forState:UIControlStateNormal];
[button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchDown];
button.frame=CGRectMake(110, 380, 100, 40);
[button setBackgroundColor:[UIColor redColor]];
[self addSubview:button];

UIButton *button2=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"橡皮擦" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchDown];
button2.frame=CGRectMake(110, 430, 100, 40);
[button2 setBackgroundColor:[UIColor redColor]];

[self addSubview:button2];

//实例化数组(用来存放移动点的数组)
lineArray =[[NSMutableArray alloc]init];
}
return self;
}

-(void)doButton:(id)button
{
[lineArray removeLastObject];
[self setNeedsDisplay];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//创建触摸事件对象
UITouch *touch = [touches anyObject];
//拿到初始点
CGPoint firstPoint = [touch locationInView:self];
//转换成value对象
NSValue *value = [NSValue valueWithCGPoint:firstPoint];
//创建存放每个点的内层数组(一条线)
NSMutableArray *pointArray = [[NSMutableArray alloc]init];
[pointArray addObject:value];
//把每一笔画对应 的数组放入外层数组
[lineArray addObject:pointArray];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
//拿到移动 时的每一个点
CGPoint currentPoint = [touch locationInView:self];
//拿到最后笔画对应的数组
NSMutableArray *pointAaary = [lineArray lastObject];
NSValue *value = [NSValue valueWithCGPoint:currentPoint];
//把移动 的每一个点放入对应的数组
[pointAaary addObject:value];
//让视图重绘(调用该方法后self的drawrect方法会被调用)
[self setNeedsDisplay];

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

}
//iOS的绘图操作是在UIView类的drawRect方法中完成的,所以如果我们要想在一个UIView中绘图,需要写一个扩展UIView 的类,并重写drawRect方法,在这里进行绘图操作,程序会自动调用此方法进行绘图。
- (void)drawRect:(CGRect)rect
{
//拿到当前绘图上下文环境
CGContextRef currentText = UIGraphicsGetCurrentContext();
//设置画笔线条的宽度
CGContextSetLineWidth(currentText, 2);
//将画笔设置为红色
CGColorRef cf = [UIColor redColor].CGColor;
CGContextSetStrokeColorWithColor(currentText, cf);

for (int i = 0; i < [lineArray count]; i++) {
//拿到每一个笔画对应的数组
NSMutableArray *pArray = [lineArray objectAtIndex:i];
for (int j = 0; j < [pArray count]-1; j++) {

NSValue *previousValue = [pArray objectAtIndex:j];
NSValue *currentValue = [pArray objectAtIndex:j+1];

CGPoint previousPoint = [previousValue CGPointValue];
CGPoint currentValuePoint = [currentValue CGPointValue];
//设置画笔的起点
CGContextMoveToPoint(currentText, previousPoint.x, previousPoint.y);
//设置两点确定一条直线的另一点
CGContextAddLineToPoint(currentText, currentValuePoint.x, currentValuePoint.y);
}
//提交描绘的轨迹,这才是真正画线的地方
CGContextStrokePath(currentText);
}


}
@end