class ViewController: UIViewController {
var 輸入框一 : UITextField?
var 輸入框二 : UITextField?
var 計算結(jié)果 : UILabel?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() -> ()
{
//第一個輸入框
let oneText = UITextField(frame: CGRect(x: 10, y: 100, width: 80, height: 25))
oneText.text = "0"
oneText.textAlignment = .center
oneText.borderStyle = .roundedRect
view.addSubview(oneText)
輸入框一 = oneText
//加號lanel
let 加號 = UILabel(frame: CGRect(x: 100, y: 100, width: 25, height: 25))
加號.text = "+"
加號.textAlignment = .center
view.addSubview(加號)
//第二個輸入框
let twoText = UITextField(frame: CGRect(x: 135, y: 100, width: 80, height: 25))
twoText.text = "0"
twoText.textAlignment = .center
twoText.borderStyle = .roundedRect
view.addSubview(twoText)
輸入框二 = twoText;
//等號按鈕
let 等號 = UIButton()
等號.setTitle("=", for: UIControlState(rawValue: 0))
等號.setTitleColor(UIColor.black(), for: UIControlState(rawValue: 0))
等號.frame = CGRect(x: 225, y: 100, width: 25, height: 25)
// 等號.layer.borderWidth = 1
// 等號.layer.borderColor = UIColor.blue().cgColor
view.addSubview(等號)
等號.addTarget(self, action: #selector(calc), for: .touchUpInside)
//結(jié)果label
let 結(jié)果 = UILabel(frame: CGRect(x: 260, y: 100, width: 50, height: 25))
結(jié)果.textAlignment = .left
結(jié)果.text = "0"
view.addSubview(結(jié)果)
計算結(jié)果 = 結(jié)果
}
func calc() -> ()
{
print(#function)
// 結(jié)算結(jié)果?.text = "\(Int(輸入框一?.text) ?? "" + Int(輸入框二?.text) ?? "" )"
guard let num1 = Int(輸入框一?.text ?? ""), num2 = Int(輸入框二?.text ?? "") else{
print("請輸入數(shù)值")
return
}
計算結(jié)果?.text = "\(num1+num2)"
}
}

EB558BFD-BD48-4CEB-AE83-B138C272C034.png