IOS入門之建立視圖和控件綁定

學習IOS幾天了,跟着教程作了兩個小應用了,如今先來總結一下。今天就是建立視圖和綁帶到代碼了。其實就是常見的MVC模式實現。ide

使用的Xcode版本是8.2。佈局

在Xcode建立項目以後,默認就會建立一個Main.stroyborad,程序的入口也就是這裏,能夠在GeneralDeployment Info裏的Main Interface修改入口storyboard爲其餘的。學習

在項目的目錄中還能看見自動建立的ViewController類,其實就是一個ViewController對應一個界面。控件庫中自帶了幾個ViewController,新建項目時,Single View Application 就是建立一個空白的ViewController。Tabbed Application就是建立一個Tab Bar Controller。atom

~~

在MVC模式中設計

* M -- 數據模型
* V -- View 對應這裏的storyboard上的界面
* C -- Controller 對應這裏的ViewController類
  • 經過storyboard,咱們設計界面,而後經過制定界面控件和ViewController類的關係,達到View和Controller綁定。
  • 經過storyboard,還能夠設計界面間的跳轉segue
  • 上圖中的ViewController就是整個storyboard的root view controller

建立好擺放控件界面以後,就能夠開始擺放控件和將控件遇ViewController綁定了code

1 擺放控件

將控件從控件庫,拖動到界面上就ok。orm

2 設置控件樣式

選中控件,在右側的inspector面板裏選擇button的類型、狀態、標題、文字顏色、文字大小等屬性blog

3 將控件與controller綁定

connect inspector

選中控件,在右側的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和控制器的方法,其餘控件也相似。

小生入門,有何不對之處,還望指出。^_^

相關文章
相關標籤/搜索