返回
SwiftUI 折扣计算器 App 实战:轻松计算折扣,买买买更划算!
IOS
2024-01-08 19:41:00
在上一章中,我们完成了折扣计算器的样式部分。在本章中,我们将重点介绍如何设计折扣计算器的逻辑,来实现折扣计算的功能。我们首先需要定义一些变量来存储商品原价、折扣类型和折扣金额。然后,我们需要编写代码来计算折扣价格。最后,我们将把折扣价格显示在用户界面上。
定义变量
import SwiftUI
struct DiscountCalculatorView: View {
@State private var originalPrice: Double = 0.0
@State private var discountType: DiscountType = .fixed
@State private var discountAmount: Double = 0.0
@State private var discountPrice: Double = 0.0
enum DiscountType {
case fixed
case percentage
case fullReduction
}
var body: some View {
// ...
在上面的代码中,我们定义了三个变量:
originalPrice
:商品原价discountType
:折扣类型discountAmount
:折扣金额discountPrice
:折扣价格
我们还定义了一个枚举类型DiscountType
来表示折扣类型。DiscountType
枚举有三个成员:fixed
、percentage
和fullReduction
,分别表示固定折扣、百分比折扣和满减折扣。
计算折扣价格
func calculateDiscountPrice() {
switch discountType {
case .fixed:
discountPrice = originalPrice - discountAmount
case .percentage:
discountPrice = originalPrice * (1 - discountAmount / 100)
case .fullReduction:
discountPrice = max(originalPrice - discountAmount, 0)
}
}
在上面的代码中,我们定义了一个函数calculateDiscountPrice()
来计算折扣价格。calculateDiscountPrice()
函数会根据折扣类型来计算折扣价格。对于固定折扣,折扣价格等于商品原价减去折扣金额。对于百分比折扣,折扣价格等于商品原价乘以折扣金额的补码。对于满减折扣,折扣价格等于商品原价减去折扣金额,但不能小于0。
显示折扣价格
var body: some View {
// ...
Text("折扣价:\(discountPrice, specifier: "%.2f")")
.font(.title2)
.foregroundColor(.blue)
// ...
在上面的代码中,我们在用户界面上显示了折扣价格。我们使用Text()
视图来显示折扣价格,并使用specifier
参数来指定折扣价格的格式。
现在,我们已经完成了折扣计算器的逻辑部分。在下一章中,我们将把折扣计算器 App 部署到 App Store,以便你可以在你的 iPhone 或 iPad 上使用它。