IOS學習-HelloWorld
1.建立項目ButtonFun
在xcode 中File --> New --> Project 選擇Single View Application,點擊next,
在Product Name 欄輸入ButtonFun,Device欄選擇iphone,點擊Next,選擇項目存放位置,點擊Create建立項目
2.串連xib和ViewController檔案
xcode使用故事板,如果不需要直接刪除即可,建立ViewController.xib : File --> New -->File 在彈出框中左側選擇User Interface ,右側選擇View,點擊Next,輸入名稱ViewController點擊create即可建立ViewController.xib檔案
點擊ViewController.xib檔案,點擊左側第一個立方體File's Owner,然後在右側選項卡頂部第三個選項卡下Custom Class 的class 中輸入ViewController確定即可。
在ViewController.m檔案中viewDidLoad方法中添加如下代碼即可載入xib檔案:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIView *rootView = [[[NSBundle mainBundle]loadNibNamed:@"ViewController" owner:self options:nil]lastObject]; self.view = rootView;}
3.添加組件
開啟ViewController.xib,從xcode的右下角第三個選項卡中將Button 和Label拖入xib中,
點擊功能表列View --> Assistant Editor --> Show Assistant Editor 可以開啟兩個編輯欄,在左右側分別顯示ViewController.xib和ViewController.h檔案,
按住control鍵 滑鼠點擊Button拖動會出現一根藍色的線, 然後拖動到ViewController.h中,在彈出框中connection項選擇Action,name欄輸入buttonPressed點擊connect;
再次拖動Button到buttonPressed方法中進行事件綁定;
相同方法將Label拖到ViewController.h中,彈出框中connection項選擇Outlet,name欄輸入statusLabel點擊connect;
ViewController.h代碼如下:
@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UILabel *statusLabel;- (IBAction)buttonPressed:(id)sender;@end
4.實現方法
現在開啟ViewController.m方法,會有一個空的方法體:
- (IBAction)buttonPressed:(id)sender {}
添加代碼:
- (IBAction)buttonPressed:(id)sender { NSString *title = [sender titleForState:UIControlStateNormal]; _statusLabel.text = plainText;}
點擊運行,點擊按鈕,完成