[IOS]IBOutlet和IBAction的理解&&IOS应用程序启动过程&&配置键盘带Done以及点击后键盘消失

来源:互联网 发布:sysctl 优化 编辑:程序博客网 时间:2024/06/16 13:39

一:关于代码中IBOutlet和IBAction的理解

在Code和UI之间建立连接之后,我们经常会在Code中看到IBOutlet和IBAction类型的属性和方法,一直很奇怪这是什么样一个类型。比如IBAction类型的方法,查看其具体的方法体实现,发现并无返回值,那么为什么这个方法被定义为IBAction呢。查阅了相关文档之后终于知道在Code这边为什么会有这么一种看似反常的情况了。在网上看到了这么一段话,也就是说在编译器看来这两个东西一个代表 空,一个代表void,那么自然这种写法在编译器看来是合法的了,但是这个两个标志给IB怎么看暂时我还不理解,待后续补充。

You might be wondering just what IBAction and IBOutlet are. Are they part of the Objective-C language?
Nope. They’re good old-fashioned C pre-processor macros. If you go into the AppKit.framework and look at the NSNibDeclarations.h header file, you’ll see that they’re defined like this:
#ifndef IBOutlet  
#define IBOutlet  
#endif 

#ifndef IBAction  
#define IBAction void  
#endif  
Confused? These two keywords do absolutely nothing as far as the compiler is concerned. IBOutlet gets entirely removed from the code before the compiler ever sees it. IBAction resolves to a void return type, which just means that action methods do not return a value. So, what’s going on here? 
The answer is simple, really: IBOutlet and IBAction are not used by the compiler. They are used by Interface Builder. Interface Builder uses these keywords to parse out the outlets and actions available to it. Interface Builder can only see methods that are prefaced with IBAction and can only see variables or properties that are prefaced with IBOutlet. Also, the presence of these keywords tells other programmers, looking at your code in the future, that the variables and methods in question aren’t dealt with entirely in code. They’ll need to delve into the relevant nib file to see how things are hooked up and used.


二:IOS应用程序启动过程

整个启动过程从UIApplicationMain(位于main.m文件中)开始,通过该方法系统会创建一个应用程序(UIApplication类)的对象实例,这个对象实例先搜索Info.plist这个文件,然后从中得知初始需要加载的xib文件(xib文件主要是用户界面的信息)来显示出相应的初始界面,待应用程序对象实例创建好之后会向委托(若建立模板时选的是single view的话则此委托的类是AppDelegate类)发送消息,即调用委托的application:DidFinishLaunchingWithOptions:方法。网上找来一个iPhone应用程序生命周期的图,贴到下面:

201106070527.jpg


三:如何设置将具有文本输入的控件输入文字时显现的键盘带有Done(完成)按钮以及当点击该按钮后键盘消失

使出现键盘时带有Done(完成)按钮:

设置文本框属性,在return key下拉列表中选择Done

201106090522.jpg

实现当点击键盘上Done(完成)按钮之后键盘消失(整理自网络):

在iPhone应用程序中,当一个允许文本输入的元素变成第一响应者时,键盘就会自动显示出来,而当该元素不再处于第一响应者状态,键盘就会消失。我们不能直接向键盘发送消息,但是可以切换文本输入元素的第一响应者状态,利用该操作的附加效果来显示或消除键盘。在应用程序中,当用户点击文本字段时,该控件就会变成第一响应者,因此键盘就会显示出来。而当用户点击键盘中的Done按键时,希望键盘消失。
UITextFieldDelegate协议包含一个textFieldShouldReturn:方法,一旦用户点击Return按键,文本字段就会调用该方法(和按键的标题无关)。但将视图控制器设置成文本输入框(UITextField)的委托(Delegate),才可以实现该方法,在方法中向文本字段发送resignFirstResponder消息,这个消息的附加效果会让键盘消失。

所以先将文本框组建设置代理为当前view的视图控制器类(具体如何设置请百度),然后实现该委托的协议方法textFieldShouldReturn(类似如下实现)

- (BOOL)textFieldShouldReturn:(UITextField *)textField {if (nameTextField == textField) {[nameTextField resignFirstResponder];}return YES;}



0 0
原创粉丝点击