Day29: Picker controller

前言

今天要在 RecipeDetailView 中添加 Picker controller,
使其能够通过选择不同的份数来显示不同量的食谱。

实作

  • 在 RecipeDetailView 中 增加 Picker 并选用 segment style

  • 更改 ingredient 数据

    这段 code 就显示 RecipeDetailView 中的 ingredient 数据,
    因为我们要做一些数学运算才可以得出不同份数的 ingredients,
    因为这些运算在其他地方也可能用到,
    所以放在管理逻辑的 ViewModel 里。
  1. 宣告 getPortion method
    并宣告为静态方法:
  2. 进入 RecipeDetailView 修改 ingredients
  3. ingredient portion
    新建一个 group 放入算法:

    具体的计算份量的 function 内容:
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 呈现:


<<:  [Day29] React Testing Library 的一些实用的小技巧

>>:  Day29 - Exploitation- Linux kernels 漏洞

[VSCode Extension] VSCodeVim: 系列文目录

大家好,我是韦恩。 这个系列章节我们将会介绍VSCodeVim的使用与教学。 先前我们介绍过了VSC...

Day01: 01 - 前置准备: 版面设计、安装、开启专案

Hello! 我是Charlie。 在这「30天肝出购物网站」系列文章中,我将与大家分享如何使用Dj...

30天学会 Python: Day 16-图片处理

PIL Python 中用於图片处理的套件 读取图片 from PIL import Image i...

Day 08 设置关键字的基本 sense

在设置关键字的时候,有些 NG 行为是不能犯的,今天就想跟大家聊聊,当我们在揣测消费者的心思时,哪些...

认识 Java 基础 第一天~

报名铁人赛希望可以有每天学习一点的动力跟每天消化一点的开始! 初次报名,请多多指教XD 因为不知道要...