swift app : 做点小事儿

基于之前提到的脚手架,我们再次创建一个swift app,这次做点小东西:

  1. 界面包括一个按钮和一个标签标签初始值为0

  2. 当点击按钮时,标签的数字会被累加1

代码如下:

import UIKit
    @UIApplicationMain
    class AppDelegate: UIResponder,UIApplicationDelegate {
        var window: UIWindow?
        func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let page = Page1()
            self.window!.rootViewController = page
            self.window?.makeKeyAndVisible()
            return true
        }
    }
    class Page1: UIViewController {
        var count = 0
        var label : UILabel!
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = .white
            label   = UILabel()
            label.frame = CGRect(x: 100,y: 100,width: 20,height: 50)
            label.text =  "0"
            view.addSubview(label)
            let button   = UIButton(type: .system)
            button.frame = CGRect(x: 120,height: 50)
            button.setTitle("+",for: .normal)
            button.addTarget(self,action: #selector(Page1.buttonAction(_:)),for: .touchUpInside)
            view.addSubview(button)
        }
        func buttonAction(_ sender:UIButton!){
            self.count +=  1
            label.text =  self.count.description
        }
    }

编译运行后会看到界面上的按钮和标签,点击按钮标签的值加1,说明App满足我们的最初需求。

代码解释下:

  1. 这次设置为APPDelegate内的rootViewController为一个继承与UIViewController的类

  2. UIViewController类内属性view可以把其他view加入其内,

  3. 按钮的类为UIButton,可以通过属性frame设置位置和大小,可以通过UIViewController.view对象的方法addSubview把按钮加入到UIViewController内

  4. 标签的类为UILabel,可以通过属性frame设置位置和大小,可以通过UIViewController.view对象的方法addSubview把按钮加入到UIViewController内

  5. button可以添加事件,通过方法

    button.addTarget(self,for: UIControlEvents.touchUpInside)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...