Swift加法计算器

前端之家收集整理的这篇文章主要介绍了Swift加法计算器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
//  ViewController.swift
//  Swift加法计算器
//
//  Created by hehongbo on 16/8/31.
//  Copyright © 2016年 hhb. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var numtext1:UITextField?
    var numtext2:UITextField?
    
    var resultLabel:UILabel?
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    // 计算
    func clac() {
        print("\(numtext1?.text) == \(numtext2?.text)")
        // 将文本框内容转换为数值
        // 先测试:let num1 = Int(numtext1?.text ?? "")
//        let num1 = Int(numtext1?.text ?? "")
//        let num2 = Int(numtext2?.text ?? "")
        
        guard let num1 = Int(numtext1?.text ?? ""),num2 = Int(numtext2?.text ?? "") else {
            
                print("必须都输入数字才能计算")
            return
        }
        // 处理结果
        resultLabel?.text = "\(num1 + num2)"
        
    }

    func setupUI() -> () {
        // 1.两个textField
        let tf1 = UITextField(frame: CGRect(x: 20,y: 20,width: 100,height: 30))
        tf1.borderStyle = .roundedRect
        tf1.text = "0"
        
        view.addSubview(tf1)
        
        let tf2 = UITextField(frame: CGRect(x: 140,height: 30))
        tf2.borderStyle = .roundedRect
        tf2.text = "0"
        
        view.addSubview(tf2)
        
        // 记录属性
        numtext1 = tf1
        numtext2 = tf2
        
        
        // 2.三个label
        let l1 = UILabel(frame: CGRect(x: 120,width: 20,height: 30))
        l1.text = "+"
        l1.textAlignment = .center
        
        view.addSubview(l1)
        
        let l2 = UILabel(frame: CGRect(x: 240,height: 30))
        l2.text = "="
        l2.textAlignment = .center
        
        view.addSubview(l2)
        
        let l3 = UILabel(frame: CGRect(x: 250,width: 60,height: 30))
        l3.text = "0"
        l3.textAlignment = .right
        
        view.addSubview(l3)
        
        resultLabel = l3
        
        // 3.一个button
        let btn = UIButton()
        btn.setTitle("计算",for: UIControlState(rawValue: 0))
        btn.setTitleColor(UIColor.black(),for: UIControlState(rawValue: 0))
        btn.sizeToFit()
        btn.center = view.center
        view.addSubview(btn)
        
        btn.addTarget(self,action: #selector(clac),for: .touchUpInside)
        
    }

}

猜你在找的Swift相关文章