今天要在 RecipeDetailView 中添加 Picker controller,
使其能夠通過選擇不同的份數來顯示不同量的食譜。
static func getPortion(ingredient:Ingredients, recipeServings:Int, targetServings: Int ) -> String {
var portion = ""
var numerator = ingredient.num ?? 1
var denominator = ingredient.denom ?? 1
var wholePortion = 0
if ingredient.num != 0 {
denominator *= recipeServings
numerator *= targetServings
let divisor = Rational.greatestCommonDivisor(numerator, denominator)
numerator /= divisor
denominator /= divisor
if numerator >= denominator {
wholePortion = numerator / denominator
numerator = numerator % denominator
portion += String(wholePortion)
}
if numerator > 0 {
portion += wholePortion > 0 ? " " : ""
portion += "\(numerator)/\(denominator)"
}
}
if let unit = ingredient.unit {
portion += ingredient.num == nil && ingredient.denom == nil ? "" : " "
return portion + unit
}
return portion
}
修改單位的單複數:
if var unit = ingredient.unit {
if wholePortion > 1 {
if unit.suffix(2) == "ch" {
unit += "es"
}
else if unit.suffix(1) == "f" {
unit = String(unit.dropLast())
unit += "ves"
}
else {
unit += "s"
}
}
portion += ingredient.num == nil && ingredient.denom == nil ? "" : " "
return portion + unit
}
最後的 view 呈現: