SwiftUI实战项目

该博客展示了如何使用SwiftUI创建一个简单的应用,用于计算聚会中每个人应付的金额。用户可以输入总费用,选择人数和小费百分比,应用会自动计算每个人平摊的费用。代码中包括了TextField、Picker等UI组件的使用,以及计算逻辑的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import SwiftUI

struct TipPageView: View {
    
    /**
      需求:输入费用,每个人AA多少钱
     */
    
    @State private var checkAmout = ""
    @State private var numberOfPeople = 0
    @State private var tipPercentage = 2
    
    let tipPercentArray = [10,15,20,25,50]
    
    var totalPerPerson:Double {
        //一共有多少人
        let peopleCount = Double(numberOfPeople+1)
        
        //选择的费率
        let tipSelection = Double(tipPercentArray[tipPercentage])
        
        //输入的价格
        let orderAmount = Double(checkAmout) ?? 0
        
        //小费钱数
        let tipValue = orderAmount / 100 * tipSelection
        
        //总价格
        let grandTotal = orderAmount + tipValue
        
        let amountPerperson = grandTotal / peopleCount
        
        return amountPerperson
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section{
                    TextField("Amount", text: $checkAmout).keyboardType(.decimalPad)
                    Picker("Number of person",selection: $numberOfPeople){
                        ForEach(1 ..< 10){
                            Text("\($0)people")
                        }
                    }
                }
                Section(header: Text("How much tip do you want to leave?")) {
                    Picker("Tip percentage",selection: $tipPercentage){
                        ForEach(0 ..< tipPercentArray.count){
                            Text("\(self.tipPercentArray[$0])%")
                        }
                    }.pickerStyle(SegmentedPickerStyle())//分段选择器
                }
                Section{
                    Text("$\(totalPerPerson,specifier:"%.2f")")
                }
            }
            .navigationTitle("WeSplit")
        }
        
    }
}

//专门供Xcode使用以显示浏览UI设计和代码
struct TipPageView_Previews: PreviewProvider {
    static var previews: some View {
        TipPageView()
    }
}

UI效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值