class ViewController: UIViewController {
var 输入框一 : UITextField?
var 输入框二 : UITextField?
var 计算结果 : 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)
//结果label
let 结果 = UILabel(frame: CGRect(x: 260, y: 100, width: 50, height: 25))
结果.textAlignment = .left
结果.text = "0"
view.addSubview(结果)
计算结果 = 结果
}
func calc() -> ()
{
print(#function)
// 结算结果?.text = "\(Int(输入框一?.text) ?? "" + Int(输入框二?.text) ?? "" )"
guard let num1 = Int(输入框一?.text ?? ""), num2 = Int(输入框二?.text ?? "") else{
print("请输入数值")
return
}
计算结果?.text = "\(num1+num2)"
}
}
Swift实现简单加法计算器
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...