制作一个简单的计算器应用是一个很好的Swift和iOS开发入门项目。以下是一个详细的步骤指南,帮助你创建一个基本的计算器应用。
在 Main.storyboard
中设计计算器的用户界面。你可以使用按钮、标签和堆栈视图来布局计算器。
Main.storyboard
。UILabel
到视图控制器顶部,用于显示结果。UIButton
创建数字按钮(0-9)和操作按钮(+、-、*、/、=、C)。UIStackView
来组织按钮,使其布局整齐。在 ViewController.swift
中实现计算器的逻辑。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var displayLabel: UILabel!
private var isFinishedTypingNumber: Bool = true
private var currentValue: Double {
get {
guard let number = Double(displayLabel.text!) else {
fatalError("Cannot convert display label text to a Double.")
}
return number
}
set {
displayLabel.text = String(newValue)
}
}
private var firstNumber: Double = 0
private var operation: String = ""
@IBAction func numberPressed(_ sender: UIButton) {
if let numberValue = sender.currentTitle {
if isFinishedTypingNumber {
displayLabel.text = numberValue
isFinishedTypingNumber = false
} else {
displayLabel.text = displayLabel.text! + numberValue
}
}
}
@IBAction func operationPressed(_ sender: UIButton) {
isFinishedTypingNumber = true
firstNumber = currentValue
if let operationValue = sender.currentTitle {
operation = operationValue
}
}
@IBAction func equalsPressed(_ sender: UIButton) {
isFinishedTypingNumber = true
let secondNumber = currentValue
var result: Double = 0
switch operation {
case "+":
result = firstNumber + secondNumber
case "-":
result = firstNumber - secondNumber
case "*":
result = firstNumber * secondNumber
case "/":
result = firstNumber / secondNumber
default:
fatalError("The operation passed in does not match any of the cases.")
}
currentValue = result
}
@IBAction func clearPressed(_ sender: UIButton) {
displayLabel.text = "0"
isFinishedTypingNumber = true
firstNumber = 0
operation = ""
}
}
Main.storyboard
。ViewController.swift
。Control
键并从 UILabel
拖动到 ViewController.swift
,创建一个 IBOutlet
,命名为 displayLabel
。Control
键并从每个数字按钮拖动到 ViewController.swift
,创建一个 IBAction
,命名为 numberPressed
。Control
键并从每个操作按钮(+、-、*、/)拖动到 ViewController.swift
,创建一个 IBAction
,命名为 operationPressed
。Control
键并从等号按钮(=)拖动到 ViewController.swift
,创建一个 IBAction
,命名为 equalsPressed
。Control
键并从清除按钮(C)拖动到 ViewController.swift
,创建一个 IBAction
,命名为 clearPressed
。Cmd + R
)。领取专属 10元无门槛券
手把手带您无忧上云