#22 換算App | 多人分攤計算機

練習字串轉數字,optional binding,收鍵盤

最近聚餐越來越多,下個月的聖誕節🎄、年底忘年會準備陸續開始啦~
趕快做一個不管是聚餐或是一起買禮物,多人分攤的計算機!

成品如下⬇️

起始畫面

可利用storyboard來設定,也可直接寫成程式碼

🔹placeholder > 提示文字,當開始輸入後即消失

🔹clear button > 有四種功能,這次選is always visible ,表示一直都會顯示Clear Button,一個灰色的叉叉

🔹keyboard type > 選擇數字鍵盤

這次只有兩個IBAction,分別是清除和計算

計算

  1. 當按下計算時,呼叫resignFirstResponder(),把鍵盤收起來
priceTextField.resignFirstResponder()
tipTextField.resignFirstResponder()
memberTextField.resignFirstResponder()

2. 計算總金額、小費及均攤的費用

利用if 判斷常數(變數)是否有值
若常數(變數)有值,加上!來讀取存取的內容

當輸入匡沒有填寫時顯示0
if priceTextField.text == "" || tipTextField.text == "" || memberTextField.text == "" {
totalPriceLable.text = "0"
tipTextField.text = "0"
memberTextField.text = "0"
}else{
let tip = Double(priceTextField.text!)! * Double(tipTextField.text!)! / 100
let total = Double(priceTextField.text!)! + tip
let share = total / Double(memberTextField.text!)!

totalPriceLable.text = String(total)
totalTipsLable.text = String(tip)
averagePriceLable.text = String(share)

🔆 GitHub

參考文章

--

--