我以前做的swift笔记, 之前都是整理在onenote上, 最近想到整理出博客. 也方便自己查找, 可以当做自己的一份文档.
import UIKit
class ViewController: UIViewController {
var numText1: UITextField?
var numText2: UITextField?
var sumLabel: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
let textField1 = UITextField(frame: CGRect(x: 20, y: 40, width: 100, height: 30))
numText1 = textField1
textField1.borderStyle = UITextBorderStyle.roundedRect
textField1.text = "0"
view.addSubview(textField1)
let textField2 = UITextField(frame: CGRect(x: 140, y: 40, width: 100, height: 30))
numText2 = textField2
textField2.borderStyle = UITextBorderStyle.roundedRect
textField2.text = "0"
view.addSubview(textField2)
let label1 = UILabel(frame: CGRect(x: 120, y: 40, width: 20, height: 30))
label1.text = "+"
label1.textAlignment = .center
view.addSubview(label1)
let label2 = UILabel(frame: CGRect(x: 240, y: 40, width: 20, height: 30))
label2.text = "="
label2.textAlignment = .center
view.addSubview(label2)
let label3 = UILabel(frame: CGRect(x: 260, y: 40, width: 50, height: 30))
sumLabel = label3
label3.text = "0"
label3.textAlignment = .right
view.addSubview(label3)
let button1 = UIButton()
button1.center = view.center
button1.setTitle("计算", for: .normal)
button1.sizeToFit()
button1.setTitleColor(UIColor.black, for: .normal)
button1.addTarget(self, action: #selector(calc), for: .touchUpInside)
view.addSubview(button1)
}
func calc() {
print(#function)
let num1 = Int(numText1?.text ?? "")
print(num1)
let num2 = Int(numText2?.text ?? "")
guard let text1 = num1,
let text2 = num2 else {
print("必须都输入数字才能计算")
return
}
sumLabel?.text = "\(text1 + text2)"
}
}
网友评论