轉自:http://blog.csdn.net/jeepxiaozi/article/details/8871844
學習了一些IOS基本的常用控件之後,我們今天嘗試來寫一個點擊按鈕實現更換Label文字的App,屬於基本入門篇。
1. 創建一個新的project,旋轉“Single View Application”,取名爲ChangeButton,然後保存。
2. 添加一個Button和一個Label
選擇project navigate中的“ECViewController.xib”,找到Button按鈕將其直接拖拽到裏面就可以了。
3. 爲按鈕添加一個事件
首先選擇Editor中的“Show the Assistant Editor”按鈕,
然後按住control鍵不放,鼠標點着控件拖拽到的ECViewController.h,會有相應的提示,如下所示:
然後將彈框:
改爲
我們來看下ECViewController.h中的代碼:
- #import <UIKit/UIKit.h>
- @interface ECViewController : UIViewController
- - (IBAction)pressBtn:(UIButton *)sender;
- @end
- - (IBAction)pressBtn:(UIButton *)sender {
- }
添加Outlet的方法和Action是一樣的,就是參數會略有不同。
點擊Connect完成之後,ECViewController.h文件中會添加如下代碼:
- @property (weak, nonatomic) IBOutlet UILabel *txtText;
然後在ECViewController.cpp 文件中添加如下代碼:
@implementation ViewController
@synthesize label = _txtText;
5. 寫代碼來實現操作
在ECViewController.m文件的pressBtn方法中添加如下代碼:
- - (IBAction)pressBtn:(UIButton *)sender {
- NSString *txtContent=[sender titleForState:UIControlStateNormal];
- _txtText.text=[NSString stringWithFormat:@"%@ button pressed",txtContent];
- }
6. 編譯運行
這個就不多說了,我們之前寫過一個簡單的,我們來直接看下運行效果:
這是剛運行之後的效果,接下來我們點擊下Button按鈕,看下效果:
OK,完成,這個例子可以讓我們對響應和事件有一定的初步瞭解,接下來我們會逐步實現更多更復雜的功能。