學習IOS幾天了,跟著教程做了兩個小應用了,現在先來總結一下。今天就是創建視圖和綁帶到代碼了。其實就是常見的MVC模式實現。
使用的Xcode版本是8.2。
在Xcode創建項目之后,默認就會創建一個Main.stroyborad,程序的入口也就是這里,可以在General的Deployment Info里的Main Interface修改入口storyboard為其他的。
在項目的目錄中還能看見自動創建的ViewController類,其實就是一個ViewController對應一個界面。控件庫中自帶了幾個ViewController,新建項目時,Single View Application 就是創建一個空白的ViewController。Tabbed Application就是創建一個Tab Bar Controller。
在MVC模式中
* M -- 數據模型
* V -- View 對應這里的storyboard上的界面
* C -- Controller 對應這里的ViewController類
- 通過storyboard,我們設計界面,然后通過制定界面控件和ViewController類的關系,達到View和Controller綁定。
- 通過storyboard,還可以設計界面間的跳轉segue。
- 上圖中的ViewController就是整個storyboard的root view controller
創建好擺放控件界面之后,就可以開始擺放控件和將控件遇ViewController綁定了
1 擺放控件
將控件從控件庫,拖動到界面上就ok。
2 設置控件樣式
選中控件,在右側的inspector面板里選擇button的類型、狀態、標題、文字顏色、文字大小等屬性
3 將控件與controller綁定
選中控件,在右側的connection inspector面板中,可以看見button的連接屬性
- Triggered Segues 這個action連接到一個界面時,點擊button就將調轉到連接的界面
- Outlet Collections button將作為一個屬性集合的一員
- Sent Events 當button的不同點擊事件觸發時,連接到上面的方法就被觸發
- Refrencing Outlets button作為一個類的屬性,一般就是button所在界面的ViewController類的屬性
button可以作為類屬性的同時,將自己的事件與類的方法綁定;也可制作為屬性,或者只綁定事件。
4 開始操作
有2種方式,可以進行綁定
- 1 在controller類里定義屬性和方法,再手動綁定
-
1
button的屬性: @property(nonatomic,weak)IBOutlet UIButton* button; button的事件: - (IBAction)clickButton:(id)sender;
2 在button的connection inspector面板中,將屬性或事件綁定到button屬性和clickButton方法上
3 綁定之后,就能屬性是和View Controller綁定的;touch up side 事件是和View Controller里的clickButton方法綁定的
-
- 2 自動綁定,好安逸。選中button所在的布局,然后點擊Xcode右上角的assistan editor。確保是在ViewController.h文件,如果不是可以在頂部切換到。接著鼠標按著button + Ctrl,往interface區中拖,按圖那樣操作,就能實現綁定。
經過上述的操作之后,我們就能點擊界面中間的button,做些事情了。
最終控制器里的代碼,加一句點擊button就修改button的文字。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *button;
- (IBAction)clickButton:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)clickButton:(id)sender {
//修改button文字
[self.button setTitle:@"clicked!" forState:UIControlStateNormal];
}
@end
以上就是在storyboard里綁定Button和控制器的方法,其他控件也類似。
小生入門,有何不對之處,還望指出。_