iphone开发学习运行的第一个例子

来源:互联网 发布:淘宝怎么添加客服旺旺 编辑:程序博客网 时间:2024/06/05 06:03

        近来,抽空看了下Objective-C和IOS开发的相关教程,初衷是因为对这些比较感兴趣,本文是参考《Iphone开发基础教程》编写的一个例子。

首先运行XCode,新建一个Single View application,如下图所示:


并取名为:Button_Fun。在该程序中将实现利用两个按钮来改变一个标签显示的内容。为了实现与Interface Builder对象的引用,UiViewController类提供了实现该功能的输出口Outlet,可以把outlet看成是指向nib对象的指针。

        为了实现上述功能,首先在Button_FunViewController.h文件中申明一个outlet输出、一个实现按钮事件的操作以及关于按钮输出口的属性(关于操作、属性等将在后续进行介绍),定义后的Button_FunViewController.h如下:

@interface Button_FunViewController : UIViewController{    IBOutlet UILabel* statusText;}@property (retain, nonatomic) UILabel* statusText;-(IBAction)buttonPressed:(id)sender;@end
        添加实现代码后,Button_FunViewController.m如下:

@implementation Button_FunViewController@synthesize statusText;-(IBAction)buttonPressed:(id)sender{    NSString* title = [sender titleForState:UIControlStateNormal];    NSString* newText = [[NSString alloc] initWithFormat:@"%@ button pressed.",title];    statusText.text = newText;    //[newText release];}- (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end 

其中@synthesize statusText; 自动实现statusText的setter和getter方法,熟悉C#和Java的人对此应该很了解。接着操作buttonPressed实现对按钮i时间的处理,并利用statusText与UiLabel对象进行显示。

        接下来,我们要实现将按钮和对应的操作buttonPressed进行关联起来。具体操作是点击xib文件,并拖放一个UILabel标签和两个Round Rect Button到界面,并进行调整和摆放后,界面如下图所示:


然后,按住Control键,拖住对应的按钮指向First Responder,并将出现对一个的界面,如下图所示:


选择buttorPressed,则可以将按钮与对应的操作进行关联。而将标签与statusText进行关联,则通过按住Control键,并点击Button_FunViewController图像,按着鼠标不放,拖拽到标签上,则会显示下图:


选择statusText则可以实现标签与输出口变量statusText的关联。

        点击command+s进行保存,点击command+B进行编译,如果没错,则点击command+R进行运行,点击Left按钮,则标签显示Left button pressed,反之,则显示Right button pressed,结果如下所示:



原创粉丝点击