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和控制器的方法,其余控件也相似。

小生入门,有何不对之处,还望指出。^_^

相关文章
相关标签/搜索