storyboard的连线

连线

目标

  • 连线前准备

    • 界面绑定代码文件
    • 界面仅仅只是用来显示,那么如果想写代码必须写在代码文件中。
    • 并且代码只能写在跟这个界面所绑定的代码文件中
    • 因为所有界面内容都在ViewController里面,所以要点黄色的“小铜钱”给这个ViewController绑定一个代码文件,绑定好后就可以把代码和连线弄在这个代码文件里了
  • 连线的目的

    • 通过连线才能够访问 Interface Builder 中控件的属性和方法
    • 要访问 Interface Builder 中控件的属性,需要连接 IBOutlet
    • 如果要监听 Interface Builder 中控件的事件,需要连接 IBAction
    • IBOutlet 可以连接到私有扩展中
    • IBAction 可以连接到实现中
    • IB 就是 Interface Builder 的缩写
  • 掌握几种连线的方式

    • Interface Builder 到源代码
  • 常见连线错误

连线演练

简单的加法计算器代码实现

复制代码
@interface GLMainViewController ()
@property (weak, nonatomic) IBOutlet UITextField *num1Text;
@property (weak, nonatomic) IBOutlet UITextField *num2Text;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@end

@implementation GLMainViewController

/// 计算结果
- (IBAction)calculate {
    // 1. 获取界面结果数值
    NSInteger num1 = _num1Text.text.integerValue;
    NSInteger num2 = _num2Text.text.integerValue;

    // 2. 计算结果
    NSInteger result = num1 + num2;

    // 3. 设置结果
    _resultLabel.text = @(result).description;
}

@end
复制代码

常见连线错误

  • 连线出现的愿意

    • 错将方法连接成了属性,又删除了
    • 连接完属性或者方法后改名了
    • ……
  • 如果连线错误运行程序时,程序会崩溃在 main.m,并且提示以下信息:

* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key num3Text.'

翻译

由于 NSUnknownKeyException(未知的键值异常) 导致应用程序终止,CZMainViewController 这个类没有 num3Text

  • 代码中检查连线情

  • Interface Builder 中检查连线情况

解决连线的重要技巧

连线完成后,立即 cmd + r 执行程序,不要等到写了很多代码之后再运行!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值