#38 貓頭鷹小費計算機APP

熟悉型別轉換、數字鍵盤設定與收合、Tap 手勢偵測

功能:

  • 型態轉換:字串轉數字、數字轉字串
  • 小數點位數呈現
  • UITextField 的 action event
  • optional變數
  • 點擊計算按鈕算小費
  • 金額或小費百分比的內容改變時,重新計算小費。
  • 鍵盤需設定數字鍵盤 ,而且可以收鍵盤。搭配偵測 tap 手勢觸發收鍵盤(Tap Gesture Recognizer)
  • 輸入人數,算出每個人要出多少錢。
  • text field 輸入數字時即時更新運算的結果。

先在 Playground 試算一下小費計算與分攤的公式

基本排版與元件設定

回到 xcode 進行排版
Text Field 設定有清除鈕,鍵盤類型選擇 Number Pad 只顯示數字

建立 IBOutlet

分別為 TextField 與 Label 建立 IBOutlet

@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var taxTextField: UITextField!
@IBOutlet weak var peopleTextField: UITextField!
//計算結果
@IBOutlet weak var totalPriceLabel: UILabel!
@IBOutlet weak var taxPriceLabel: UILabel!
@IBOutlet weak var onePriceLabel: UILabel!

點擊計算按鈕收起鍵盤

為計算按鈕拉 IBAction 並設定,點擊計算按鈕會收起鍵盤,才不會擋到畫面,使用 resignFirstResponder()

@IBAction func calculator(_ sender: UIButton) {
priceTextField.resignFirstResponder()
taxTextField.resignFirstResponder()
peopleTextField.resignFirstResponder()
}

用 if else 判斷使用者是否有輸入數字,如果沒有的話就顯示0

totalPriceLabel.text = "0"
taxPriceLabel.text = "0"
onePriceLabel.text = "0"

稅金計算與型別轉換

因為從 TextField 取得的文字是字串,所以要做計算就必須轉型別成 Double
計算後的結果要在 Label 裡顯示時,必須再轉成 String

priceTextField.text 加入括號外面包 Double ,可以把字串轉為浮點數

total 用括號包起來外面加 String 可以把福點數轉型別為字串

if priceTextField.text == "" || taxTextField.text == "" || peopleTextField.text == ""{
totalPriceLabel.text = "0"
taxPriceLabel.text = "0"
onePriceLabel.text = "0"
}else{
// 計算稅金
let tax = Double(priceTextField.text!)! * Double(taxTextField.text!)! / 100
let total = Double(priceTextField.text!)! + tax
let share = total / Double(peopleTextField.text!)!

totalPriceLabel.text = String(total)
taxPriceLabel.text = String(tax)
onePriceLabel.text = String(share)

}

清除按鈕讓文字匡歸零

@IBAction func pressClearBtn(_ sender: UIButton) {
priceTextField.text = ""
taxTextField.text = ""
peopleTextField.text = ""
totalPriceLabel.text = "0"
taxPriceLabel.text = "0"
onePriceLabel.text = "0"
}

Tap 偵測手勢

最後搭配偵測 tap 手勢觸發收鍵盤 Tap Gesture Recognizer
當點擊畫面任意地方的時候會收起鍵盤。

在 Storyboard 加入 Tap Gesture 元件,拉 IBAction

加入這段程式碼 view.endEditing(true)

@IBAction func onTap(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}

Tap Gesture Recognizer 無效沒反應?

如果發現點任意地方都不會收起鍵盤,應該是連結的對象不對,因為一開始我也是發現點擊畫面鍵盤沒反應,檢查後發現連到背景圖上了。

在 Tap Gesture Recognizer 上點擊 control + 滑鼠左鍵 檢查是不是連到 View 上

如果不是,請按X刪除 再重新拉線連到 View上

操作動畫

--

--

Rose
彼得潘的 Swift iOS / Flutter App 開發教室

Coding & Design 一直在學習的路上,從未停止,一有空檔就會摸摸我的兔子🐰