iOS&&Swift入门(三)Button/按键

来源:互联网 发布:teamviewer mac 破解版 编辑:程序博客网 时间:2024/06/05 17:17

这篇主要想建立一个小App,可以按对应button来更换显示的文字~


  • 建project
  • 点开Main.storyboard(暂时disable size classes)(详见(一)), 往上面拖一个label,两个button(在右下角search lable/button然后拖拽入viewController就可以啦)如图(我还贪心地换了一下背景色啦…)

这里写图片描述

上面的Hello World是Label,剩下两个是Button

  • 在右上角选这里写图片描述中间这个就会出现split window啦,右面的代码是ViewController.swift的, 这个是用来控制Main.storyboard这个界面上的活动的
  • 删掉class ViewController 里面的默认代码
  • 按住control,选中UI界面上的button,向右侧代码的class中拖拽,会弹出小界面如下,选择Action, UIButton然后给这个method起个名字~然后connect

    这里写图片描述

  • 选择另一个Button, 按住control,拖拽到刚刚建立的function里面(注意!两个Button功用这个method)

  • 按control,将label拖拽到class里(method外面哦)然后起个名字~这次是Outlet
    这里写图片描述

  • 完善method function,完成代码如下

import UIKitclass ViewController: UIViewController {    @IBOutlet weak var textView: UILabel!    @IBAction func buttonOnClick(sender: UIButton) {        //sender is the object that called this method (i.e.button)        let title = sender.titleForState(.Normal)!        textView.text = "You clicked the \(title) button"    }}

注意在Swift中var会定义新的可变variable, let则相当于const var, 定义不变量。这里不希望Button上面的字会变,所以把title定义成了constant

  • 可以run啦
    点击MUA~如下:
    这里写图片描述

点击Hug如下:
这里写图片描述

文字转换实现^_^iOS开发好人性化!


今日DONE~

0 0
原创粉丝点击