Ep.23[ wen’s iOS ] — 瘋狂購物UIStepper 和數字變字串練習
數字轉字串的練習也是排在作業清單中拖很久了,本次作業用逛百貨公司常常看到的保養品牌品木宣言當素材練習,剛好本週上課教到 delegate 的概念 iOS SDK 內建的 controller ,使用 UIAlertController 作為購買按鈕後的彈出視窗。
App 實作
storyboard 建立
先用 class 自創類別 Product,建立三個屬性,再來初始化 init(name: String, quantity: Int, price: Int)
用於在建立商品時設定商品的名稱、數量和價格。在初始化時,透過 self.name
、self.quantity
和 self.price
來引用屬性,self
代表正在建立的 Product
物件自身。透過這個初始化方法,一旦商品被建立,它的名稱和價格就不會再被修改,但數量可以隨時改變。
// 產品類別,封裝產品的名稱、數量和價格
class Product {
let name: String
var quantity: Int
let price: Int
init(name: String, quantity: Int, price: Int) {
self.name = name
self.quantity = quantity
self.price = price
}
}
再來建立一個商品的 Array 並分別輸入自定義的參數。
var products = [
Product(name: "產品1", quantity: 0, price: 980),
Product(name: "產品2", quantity: 0, price: 1600),
Product(name: "產品3", quantity: 0, price: 1600),
Product(name: "產品4", quantity: 0, price: 1050),
Product(name: "產品5", quantity: 0, price: 1200),
Product(name: "產品6", quantity: 0, price: 1400)
]
本篇最重要的重點來了,數字轉字串,利用 "\(products[0].quantity)"
去控制 label.text
中的文字,products[0]
是取得 products
陣列中的第一個元素,而這個元素是一個 Product
物件,因此可以透過 .
來存取該物件的屬性。在這裡,我們使用 .
來存取 quantity
屬性,這是 Product
類別中定義的一個變數。
// 更新產品數量標籤
product1Label.text = "\(products[0].quantity)"
product2Label.text = "\(products[1].quantity)"
product3Label.text = "\(products[2].quantity)"
product4Label.text = "\(products[3].quantity)"
product5Label.text = "\(products[4].quantity)"
product6Label.text = "\(products[5].quantity)"
請 chapgpt 幫我改寫有沒有更好的寫法中,總金額的部分 chatgpt 幫我利用高階函式 .reduce
改寫,而這整串程式碼是計算屬性(Computed Property)用來計算所有產品的總金額 totalMoney
。
reduce
方法接受兩個參數:
- 初始值
0
:這是totalMoney
的初始值,表示計算總金額時從0開始累加。 - 閉包 ( Closure )表達式
{ $0 + $1.quantity * $1.price }
:這是用來指定運算邏輯的閉包表達式,用於計算每個產品的金額。閉包表達式接受兩個參數$0
和$1
,代表運算的累加值和陣列中的元素(Product
物件)。在這裡,我們將$0
加上$1.quantity * $1.price
,這就是計算每個產品的金額並進行累加的邏輯。
// 總金額
var totalMoney: Int {
return products.reduce(0) { $0 + $1.quantity * $1.price }
}
接下來本週新教到的觀念 UIAlertController 直接套用,先建立 UIAlertController 參數輸入要顯示的內容,再來也要把 ok 按鍵加上去,否則彈出視窗會一直擋著畫面無法消失!用 .addAction
加入至 alert ,最後 present alert 才會正常顯示。
func showSpendingAlert() {
let alert = UIAlertController(title: "花費金額",
message: "產品1:\(products[0].quantity * products[0].price )元\n產品2:\(products[1].quantity * products[1].price )元\n產品3:\(products[2].quantity * products[2].price)元\n產品4:\(products[3].quantity * products[3].price)元\n產品5:\(products[4].quantity * products[4].price)元\n產品6:\(products[5].quantity * products[5].price)元\n總金額:\(totalMoney)元",preferredStyle: .alert)
let okAction = UIAlertAction(title: "確定", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
不過奇怪的是在跑模擬器的時後一開始出現了紅色錯誤,直到我在 AppDelegate 加上了 UIAlertViewDelegat 才能正常運作。