UIProgressView进度条

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  //创建
UIProgressView *progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
[self.view addSubview:progressView];
[progressView release];

progressView.frame = CGRectMake(20, 100, 300, 10);

//属性progress决定值的大小
//设置初始值
progressView.progress = 0;

//利用NSTimer
//创建NSTimer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];


-(void)timerAction:(NSTimer *)timer
{
if (self.progressView.progress < 1) {
self.progressView.progress += 0.01;
}
}

UISlider滑条

UIDevice提供了多种属性、类函数及状态通知,帮助我们全方位了解设备状况。从检测电池电量到定位设备与临近感应,UIDevice所做的工作就是为应用程序提供用户及设备的一些信息。UIDevice类还能够收集关于设备的各种具体细节,例如机型及iOS版本等。其中大部分属性都对开发工作具有积极的辅助作用。下面的代码简单的使用UIDevice获取手机属性。

UITextView

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
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];

self.textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 667-80, 375, 80)];

self.textView.delegate = self;

self.textView.font = [UIFont systemFontOfSize:20];

self.textView.textColor = [UIColor blackColor];

self.textView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);//添加滚动区域

self.textView.text = @"习大大";

self.textView.scrollEnabled = YES;//是否可滚动

self.textView.editable = YES;//是否可编辑

self.textView.returnKeyType = UIReturnKeyDefault;//返回键的类型

self.textView.keyboardType = UIKeyboardTypeDefault;//键盘类型

self.textView.scrollEnabled = YES;//是否可以拖动

self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度

self.textView.layer.cornerRadius = 8; //边框设置为圆角

self.textView.layer.borderWidth = 1;

// 设置边框颜色 参数2是一个数组 分别为三基色和alpha分量;
CGFloat color[]={0.5, 0.5, 0.5, 1};
self.textView.layer.borderColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(),color);
self.textView.layer.masksToBounds = YES;

// [self.textView becomeFirstResponder];//获得焦点 程序运行就获取光标

self.myView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.myView.tag = 1000;

[self.view addSubview:self.myView];

[self.myView addSubview:self.textView];

//注册通知,监听键盘弹出事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

//注册通知,监听键盘消失事件
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden) name:UIKeyboardDidHideNotification object:nil];
}

//将要开始编辑
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{

return YES;
}

//将要结束编辑
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{

return YES;
}

//开始编辑
- (void)textViewDidBeginEditing:(UITextView *)textView{

}

//结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView{

}

//焦点发生改变
- (void)textViewDidChangeSelection:(UITextView *)textView{

}

//内容发生改变编辑
- (void)textViewDidChange:(UITextView *)textView{

}

//内容将要发生改变编辑

//控制输入文字的长度和内容,可通调用以下代理方法实现
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

if (range.location>=100){
//控制输入文本的长度
return NO;
}
if ([text isEqualToString:@"\n"]) {
//禁止输入换行
return NO;
}
else{
return YES;
}
}

// 键盘弹出时
-(void)keyboardDidShow:(NSNotification *)notification{

//获取键盘高度
NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];

CGRect keyboardRect;

[keyboardObject getValue:&keyboardRect];

//调整放置有textView的view的位置

//设置动画
[UIView beginAnimations:nil context:nil];

//定义动画时间
[UIView setAnimationDuration:kAnimationDuration];

//设置view的frame,往上平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-keyboardRect.size.height-kViewHeight, 375, kViewHeight)];

[UIView commitAnimations];
}

//键盘消失时
-(void)keyboardDidHidden
{
//定义动画
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kAnimationDuration];
//设置view的frame,往下平移
[(UIView *)[self.view viewWithTag:1000] setFrame:CGRectMake(0, self.view.frame.size.height-kViewHeight, 375, kViewHeight)];
[UIView commitAnimations];
}

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

[self.textView resignFirstResponder];
}
@end

UITextField

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
  //创建 
UITextField*textfield = [[UITextField alloc]initWithFrame:CGRectMake(20,20,200,40)];
[self.window addSubview:self.myTextField];

//设置背景颜色
self.myTextField.backgroundColor = [UIColor clearColor];

//设置输入框样式
self.myTextField.borderStyle = UITextBorderStyleRoundedRect;

//密文输入
self.myTextField.secureTextEntry = YES;

//设置占位提示符
self.myTextField.placeholder = @"请输入";

//设置输入框删除按钮
self.myTextField.clearButtonMode = UITextFieldViewModeAlways;

//设置键盘类型
self.myTextField.keyboardType = UIKeyboardTypeNumberPad;


/******按按钮键盘隐藏*********************************/
//创建按钮
UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.window addSubview:Button];
Button.frame = CGRectMake(20, 80, 100, 30);
Button.backgroundColor = [UIColor cyanColor];

[Button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];

-(void) buttonAction:(UIButton *)b
{
[self.myTextField resignFirstResponder];
//取消第一响应者
}
/******************************************************/



/******按return键盘隐藏*********************************/
1.UITextFieldDelegate协议
@interface AppDelegate : UIResponder <UIApplicationDelegate,UITextFieldDelegate>

2.成为代理人
哪个输入框成为代理人哪个输入框有此功能
self.myTextField.delegate = self;

3.实现协议里的方法
//点击return建的时候被触发
通用,一个就可以给所有输入框用
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.myTextField resignFirstResponder];
return YES;

}
/******************************************************/

/******按空白处键盘隐藏*********************************/
//按空白处键盘回收
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTap:)];
[self.view addGestureRecognizer:tap];

//按空白处键盘回收调用的方法
- (IBAction)backgroundTap:(id)sender {
[self.studentDetailV.tf1 resignFirstResponder];
[self.studentDetailV.tf2 resignFirstResponder];
[self.studentDetailV.tf3 resignFirstResponder];
[self.studentDetailV.tf4 resignFirstResponder];
[self.studentDetailV.tf5 resignFirstResponder];

}
/******************************************************/

UIWebView

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
@property(nonatomic,retain)UIWebView *webView;

//创建
self.webView = [[UIWebViewalloc]initWithFrame:[[UIScreenmainScreen] bounds]];
[self.view addSubview:self.webView];

//要前往的URL
NSString *str = @"http://www.youku.com";
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

//成为代理
self.webView.delegate = self;

//自定义导航栏左右按钮
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"后退" style:UIBarButtonItemStylePlain target:self action:@selector(leftAction)];

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"前进" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];



UITextField *textf = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
textf.borderStyle = UITextBorderStyleRoundedRect;
textf.clearButtonMode = UITextFieldViewModeAlways;
self.navigationItem.titleView = textf;
textf.delegate = self;



//后退
-(void)leftAction
{
[self.webView goBack];
}
//前进
-(void)rightAction
{
[self.webView goForward];
}


UITextFieldDelegate协议方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{


if ([textField.text hasPrefix:@"http://www."]) {

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:textField.text]];
[self.webView loadRequest:request];

}else
{
NSString *str = [NSString stringWithFormat:@"http://www.%@",textField.text];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str]];
[self.webView loadRequest:request];
}
[textField resignFirstResponder];
return YES;

}

UIWindow.h详解

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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#import <Foundation/Foundation.h>//基础框架入口

#import <CoreGraphics/CoreGraphics.h>//绘图入口

#import <UIKit/UIView.h>//视图对象

#import <UIKit/UIApplication.h>//提供iOS程序运行期的协作和控制

#import <UIKit/UIKitDefines.h>//一些宏定义



NS_ASSUME_NONNULL_BEGIN



typedef CGFloat UIWindowLevel;//32位则为float | 64位为double

/*

UIEvent 触摸事件,运动事件

UIScreen 屏幕处理

NSUndoManager 记录撤销,修改操作的消息

UIViewController 视图控制器

*/

@class UIEvent,UIScreen, NSUndoManager,UIViewController;



NS_CLASS_AVAILABLE_IOS(2_0)@interface UIWindow :UIView



@property(nonatomic,strong)UIScreen *screen;

@property(nonatomic)UIWindowLevel windowLevel;

@property(nonatomic,readonly,getter=isKeyWindow)

BOOL keyWindow;

- (void)becomeKeyWindow;

- (void)resignKeyWindow;

- (void)makeKeyWindow;

- (void)makeKeyAndVisible;

@property(nullable,nonatomic,strong)UIViewController *rootViewController NS_AVAILABLE_IOS(4_0); // default is nil



/*

事件拦截分发到指定视图对象

当用户发起一个事件,比如触摸屏幕或者晃动设备,系统产生一个事件,同时投递给UIApplication,而UIApplication则将这个事件传递给特定

UIWindow进行处理(正常情况都一个程序都只有一个UIWindow),然后由UIWindow将这个事件传递给特定的对象(即first responder)并通过响应链

进行处理。虽然都是通过响应链对事件进行处理,但是触摸事件和运动事件在处理上有着明显的不同(主要体现在确定哪个对象才是他们的first

responder):

*/

- (void)sendEvent:(UIEvent *)event;



//窗口坐标系统转化

- (CGPoint)convertPoint:(CGPoint)point toWindow:(nullableUIWindow *)window;//转化当前窗口一个坐标相对另外一个窗口的坐标

- (CGPoint)convertPoint:(CGPoint)point fromWindow:(nullableUIWindow *)window;//转化另外窗口一个坐标相对于当前窗口的坐标

- (CGRect)convertRect:(CGRect)rect toWindow:(nullableUIWindow *)window;//转化当前窗口一个矩形坐标相对另外一个窗口的坐标

- (CGRect)convertRect:(CGRect)rect fromWindow:(nullableUIWindow *)window;//转化另外窗口一个矩形坐标相对于当前窗口的坐标



@end



UIKIT_EXTERN constUIWindowLevel UIWindowLevelNormal;//默认等级

UIKIT_EXTERN constUIWindowLevel UIWindowLevelAlert;//UIAlert等级

UIKIT_EXTERN constUIWindowLevel UIWindowLevelStatusBar;//状态栏等级



UIKIT_EXTERN NSString *const UIWindowDidBecomeVisibleNotification;// nil 通知对象窗口为可见

UIKIT_EXTERN NSString *const UIWindowDidBecomeHiddenNotification; // nil 通知对象窗口为隐藏

UIKIT_EXTERN NSString *const UIWindowDidBecomeKeyNotification; // nil 通知对象窗口为重要

UIKIT_EXTERN NSString *const UIWindowDidResignKeyNotification; // nil 通知对象窗口取消主窗



//当键盘显示或消失时,系统会发送相关的通知:

UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification;//通知键盘对象视图即将加载

UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification;//通知键盘对象视图完全加载

UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification;//通知键盘对象视图即将隐藏

UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;//通知键盘对象视图完全隐藏



/*

通知消息 NSNotification中的 userInfo字典中包含键盘的位置和大小信息,对应的key为

UIKeyboardFrameBeginUserInfoKey

UIKeyboardFrameEndUserInfoKey

UIKeyboardAnimationDurationUserInfoKey

UIKeyboardAnimationCurveUserInfoKey

UIKeyboardFrameBeginUserInfoKey,UIKeyboardFrameEndUserInfoKey对应的Value是个NSValue对象,内部包含CGRect结构,分别为键盘起始时和终止时的位置信息。

UIKeyboardAnimationCurveUserInfoKey对应的Value是NSNumber对象,内部为UIViewAnimationCurve类型的数据,表示键盘显示或消失的动画类型。

UIKeyboardAnimationDurationUserInfoKey对应的Value也是NSNumber对象,内部为double类型的数据,表示键盘h显示或消失时动画的持续时间



例如,在UIKeyboardWillShowNotification,UIKeyboardDidShowNotification通知中的userInfo内容为

userInfo = {

UIKeyboardAnimationCurveUserInfoKey = 0;

UIKeyboardAnimationDurationUserInfoKey = "0.25";

UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";

UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 588}";

UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 372}";

UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";

UIKeyboardFrameChangedByUserInteraction = 0;

UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";

}

在UIKeyboardWillHideNotification,UIKeyboardDidHideNotification通知中的userInfo内容为:

userInfo = {

UIKeyboardAnimationCurveUserInfoKey = 0;

UIKeyboardAnimationDurationUserInfoKey = "0.25";

UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";

UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 372}";

UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 588}";

UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";

UIKeyboardFrameChangedByUserInteraction = 0;

UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";

}

*/

UIKIT_EXTERN NSString *const UIKeyboardFrameBeginUserInfoKey NS_AVAILABLE_IOS(3_2);// NSValue of CGRect

UIKIT_EXTERN NSString *const UIKeyboardFrameEndUserInfoKey NS_AVAILABLE_IOS(3_2);// NSValue of CGRect

UIKIT_EXTERN NSString *const UIKeyboardAnimationDurationUserInfoKeyNS_AVAILABLE_IOS(3_0);// NSNumber of double

UIKIT_EXTERN NSString *const UIKeyboardAnimationCurveUserInfoKey NS_AVAILABLE_IOS(3_0);// NSNumber of NSUInteger (UIViewAnimationCurve)

UIKIT_EXTERN NSString *const UIKeyboardIsLocalUserInfoKey NS_AVAILABLE_IOS(9_0);// NSNumber of BOOL

UIKIT_EXTERN NSString *const UIKeyboardWillChangeFrameNotification NS_AVAILABLE_IOS(5_0);//键盘即将改变布局发出通知

UIKIT_EXTERN NSString *const UIKeyboardDidChangeFrameNotification NS_AVAILABLE_IOS(5_0);//键盘已经改变布局后发出通知

UIKIT_EXTERN NSString *const UIKeyboardCenterBeginUserInfoKey NS_DEPRECATED_IOS(2_0,3_2);

UIKIT_EXTERN NSString *const UIKeyboardCenterEndUserInfoKey NS_DEPRECATED_IOS(2_0,3_2);

UIKIT_EXTERN NSString *const UIKeyboardBoundsUserInfoKey NS_DEPRECATED_IOS(2_0,3_2);



NS_ASSUME_NONNULL_END

UISwitch 圆点按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//UISwitch的初始化
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(54.0f, 16.0f, 100.0f, 28.0f)];
[view addSubview:switchView];


//设置UISwitch的初始化状态
switchView.on = YES;//设置初始为ON的一边


//UISwitch事件的响应
[switchView addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];

//开启状态的颜色
switchView.onTintColor = [UIColor redColor];

//关闭状态的颜色
switchView.tintColor = [UIColor greenColor];

//圆圈的颜色
switchView.thumbTintColor = [UIColor yellowColor];

UTF-8 和 GBK 的 NSString 相互转化的方法

应用都要遇到一个很头疼的问题:文字编码,汉字的 GBK 和 国际通用的 UTF-8 的互相转化稍一不慎,
就会满屏乱码。下面介绍 UTF-8 和 GBK 的 NSString 相互转化的方法

NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
char c_test = “北京”;
int nLen = strlen(c_test);
NSString
str = [[NSString alloc]initWithBytes:c_test length:nLen encoding:enc ];
NSLog(@”str = %@”,str);

从 GBK 转到 UTF-8 用 NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000) ,
然后就可以用initWithData:encoding来实现。

从 UTF-8 转到 GBK CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000),
得到的enc却是kCFStringEncodingInvalidId。
没关系,试试 NSData *data=[nsstring dataUsingEncoding:-2147482063];

转换字符编码主要用到CFStringConvertEncodingToNSStringEncoding函数,具体的大家可以看看这个函数的用法
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);

完整代码如下:
NSURL url = [NSURL URLWithString:urlStr];
NSData
data = [NSData dataWithContentsOfURL:url];
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];

一个比较方便的转换NSString为UTF8编码的函数,大家可以试试

头文件: @interface NSString (OAURLEncodingAdditions)

  • (NSString *)URLEncodedString;
  • (NSString *)URLDecodedString;
    @end
    m文件:
    @implementation
    NSString (OAURLEncodingAdditions)

    • (NSString )URLEncodedString
      {
      NSString
      result = (NSString )CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,CFSTR(“!‘();:@&=+$,/?%#[]”),kCFStringEncodingUTF8);
      [result autorelease];
      return result;
      }
  • (NSString)URLDecodedString
    {
    NSString
    result = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,(CFStringRef)self, CFSTR(“”),kCFStringEncodingUTF8);CFSTR(“”),kCFStringEncodingUTF8);
    [result autorelease];
    return result;
    }
    @end
    如果需要转换一个NSString, 只需要

NSString temp = [@”测试utf8” URLEncodedString];
NSString
decoded = [temp URLDecodedString];

assert

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
assert宏的原型定义在<assert.h>中,其作用是如果它的条件返回错误,则终止程序执行,原型定义:


#include <assert.h>
void assert( int expression );
assert的作用是现计算表达式 expression ,如果其值为假(即为0),那么它先向stderr打印一条出错信息,然后通过调用 abort 来终止程序运行。请看下面的程序清单badptr.c:



1 #include <stdio.h>
2 #include <assert.h>
3 #include <stdlib.h>
4 int main( void )
5 {
6 FILE *fp;
7
8 fp = fopen( "test.txt", "w" );//以可写的方式打开一个文件,如果不存在就创建一个同名文件
9 assert( fp ); //所以这里不会出错
10 fclose( fp );
11
12 fp = fopen( "noexitfile.txt", "r" );//以只读的方式打开一个文件,如果不存在就打开文件失败
13 assert( fp ); //所以这里出错
14 fclose( fp ); //程序永远都执行不到这里来
15 return 0;
16 }

已放弃使用assert()的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。在调试结束后,可以通过在包含#include <assert.h>的语句之前插入 #define NDEBUG 来禁用assert调用,示例代码如下:


#include <stdio.h>
#define NDEBUG
#include <assert.h>
用法总结与注意事项:

1)在函数开始处检验传入参数的合法性如:



int resetBufferSize(int nNewSize)
{
  //功能:改变缓冲区大小,
  //参数:nNewSize 缓冲区新长度
  //返回值:缓冲区当前长度
  //说明:保持原信息内容不变 nNewSize<=0表示清除缓冲区
  assert(nNewSize >= 0);
  assert(nNewSize <= MAX_BUFFER_SIZE);
  ...
}

2)每个assert只检验一个条件,因为同时检验多个条件时,如果断言失败,无法直观的判断是哪个条件失败,如:

 不好:


assert(nOffset>=0 && nOffset+nSize<=m_nInfomationSize);
 好:


assert(nOffset >= 0);
assert(nOffset+nSize <= m_nInfomationSize);

3)不能使用改变环境的语句,因为assert只在DEBUG个生效,如果这么做,会使用程序在真正运行时遇到问题,如:
 错误:


assert(i++ < 100);
这是因为如果出错,比如在执行之前i=100,那么这条语句就不会执行,那么i++这条命令就没有执行。

 正确:


assert(i < 100);
i++;

4)assert和后面的语句应空一行,以形成逻辑和视觉上的一致感。
5)有的地方,assert不能代替条件过滤。

UIscrollView滚动时调用的方法

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
//UIscrollView开始拖拽的时候调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(@"开始拖拽");
}


//UIscrollView拖拽结束的时候调用
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSLog(@"拖拽结束");
}


//UIscrollView拖拽结束的时候调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//在滚动的时候调用
}

//UIscrollView开始减速的时候调用
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
NSLog(@"开始减速");

}

//UIscrollView减速停止的时候调用
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(@"减速停止");
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView viewWithTag:9999];
//只有实现这个方法 才能执行缩放 指定对象;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView
{
NSLog(@"缩放时一直触发");

}


- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return _imageView;
}

#pragma mark 当缩放完毕的时候调用
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
// NSLog(@"结束缩放 - %f", scale);
}

#pragma mark 当正在缩放的时候调用
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
// NSLog(@"-----");
}
|