写一个简单的加法计算器,代码如下:
class ViewController: UIViewController {
var numText1: UITextField?
var numText2: UITextField?
var resultLabel: UILabel?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Do any additional setup after loading the view, typically from a nib.
}
///button的点击方法
func calc() -> () {
print(#function)
print("\(String(describing: numText1?.text)) \(String(describing: numText2?.text))")
//将文本框内容转换为数值
guard let num1 = Int(numText1?.text ?? "") ,let num2 = Int(numText2?.text ?? "") else{
print("必须输入数字")
return
}
resultLabel?.text = "\(num2+num1)"
}
func setupUI() -> (){
//1.两个textfield
let tf1 = UITextField(frame: CGRect(x: 20, y: 20, width: 100, height: 30))
tf1.borderStyle = .line
tf1.text = "0"
view.addSubview(tf1)
let tf2 = UITextField(frame: CGRect(x: 140, y: 20, width: 100, height: 30))
tf2.borderStyle = .line
tf2.text = "0"
view.addSubview(tf2)
numText1 = tf1
numText2 = tf2
//2.三个label
let lb1 = UILabel(frame: CGRect(x: 130, y: 20, width: 10, height: 30))
lb1.text = "+"
lb1.textAlignment = .center
view.addSubview(lb1)
let lb2 = UILabel(frame: CGRect(x: 240, y: 20, width: 10, height: 30))
lb2.text = "="
lb2.textAlignment = .center
view.addSubview(lb2)
let lb3 = UILabel(frame: CGRect(x: 240, y: 20, width: 60, height: 30))
lb3.text = "0"
lb3.textAlignment = .right
view.addSubview(lb3)
resultLabel = lb3
//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(calc), for: .touchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
几行简单的代码。