您的位置:首页 > 移动开发 > IOS开发

IOS5编程--官方例子代码研究--1。helloWord

2014-05-06 14:20 417 查看
官方描述:

HelloWorld demonstrates how to use a keyboard to enter text into a text field and how to display the text in a label.

适用级别:

入门级

这个是最初级的一个例子代码,所以做为第一个研究的对象,如果你是一个有一定工作经验的开发人员,请忽略之。

这个工程中需要注意以下几个地方。

1.这个工程是一个Empty Application工程,不是一个Single View Application工程,虽然运行后看起来象一个Single View Application工程,

2.创建一个Empty Application工程后,手动加入一个MyViewController类,继承自UIViewController,同时需要选中With XIB for user interface。你自己做的时候会发现生成的文件目录和例子中不同,请忽略这个,例子是Xcode的历史版本生成的。

3.在例子中,类名是MyViewController,xib文件的名字是HelloWorld.xib,在我们自己创建的工程中,类名和xib文件的名字相同。我们的方式会更方便一些。

当然我们需要改写HelloWorldAppDelegate类中的函数applicationDidFinishLaunching中的第一行

MyViewController *aViewController = [[MyViewControlleralloc] initWithNibName:@"HelloWorld"bundle:[NSBundlemainBundle]];
更改为

MyViewController *aViewController = [[MyViewControlleralloc] initWithNibName:@"MyViewController"bundle:[NSBundlemainBundle]];

4.如果你使用了分别创建类和xib文件,类名为MyViewController,而xib文件名为HelloWorld.xib,那么必须自己修改xib文件。打开HelloWorld.xib,



选择File's Owner,在Utility area部分选择Identity inspector,在Custom Class下面修改Class中的内容,修改为MyViewController,这样的话,HelloWorldAppDelegate类中的函数applicationDidFinishLaunching中的第一行就不需要再修改了。

在Utility area上选择Attributes部分,Simulated Metrics里面的Status Bar上,选择None.

右键点击View上,选择New Referencing Outlet后面的圆点,拖拽到File's Owner上松手后,点击出现的view,保存xib文件即可。

5.在上面的xib中的view上添加三个控件,一个是Image view,一个Label,一个是Text Field,同时为后两个添加IBOutlet的指针。

关于添加IBOutlet的指针,在Xcode4.0中有了新的方式。过去的方式,我就不在这里介绍了,比较的麻烦。





确保Assistant Editor区域出现,并且是MyViewController.h文件的内容。

在Text Field上点击右键,点中New Reference Outlet后面的圆点,拖拽到Assistant Editor区域的MyViewController类的声明中,松开后,在弹出对话框中输入textField,回车即可。

同样的方式也可以快速设置IBAction。

6.在HelloWorldAppDelegate中的applicationDidFinishLaunching函数中:

[[UIApplicationsharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];

这行代码是设置iOS设备的状态栏在程序运行起来后的呈现方式的,这样设置是呈现为黑色底。缺省的灰色底。

7.UITextFieldDelegate的使用

Text Field在输入模式下,按回车,软键盘并不会消失,需要我们实现UITextFieldDelegate中的一个函数,并设置所有在viewcontroller中的Text Field的代理都是这个viewcontroller。

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {

[theTextFieldresignFirstResponder];

returnYES;

}

这个函数在键盘消失的时候会被调用。

8.例子程序中,点击界面上任何其他地方,软键盘也会消失,这个就是下面这个函数起的作用

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

{

// Dismiss the keyboard when the view outside the text field is touched.

[textFieldresignFirstResponder];

// Revert the text field to the previous value.

textField.text =self.string;

[supertouchesBegan:touches withEvent:event];

}

任何view,viewcontroller都可以重写下面四个函数来响应手指事件。

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

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

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

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

当然在iOS3.2后,增加了更多的手指事件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: