代码之家  ›  专栏  ›  技术社区  ›  Joe Vargas

只需要对swift 3中的功能提供一点指导

  •  0
  • Joe Vargas  · 技术社区  · 8 年前

    我用Swift 3创建了一个简单的提示计算器。花了整整5个小时的时间,试图将每个按钮动作的功能整合到一个功能中,结果我一无所获。所以现在每个按钮都是硬编码的。我已经上传了 VC file 发送到github供您参考。从第15行开始,你可以看到,这是我试图创建的功能,第28行是我希望每个按钮的动作都有。我没有在函数中使用数组的经验,所以这就是我在这里缺乏的地方。我知道我真的很接近解决它,但有一些经验丰富的头脑来给它一次将是有益的。提前谢谢!

    VC Screenshot

    1 回复  |  直到 8 年前
        1
  •  0
  •   Sweeper    8 年前

    你看,你所有的按钮动作都是这样的:

        let billTotal = Double(subtotalText.text!)!
        let grandTotal = (billTotal * tipArray[x]) + billTotal
    
        //return grandTotal
        totalAmountLbl.text = String(format: "%.2f", grandTotal)
    

    x 价值为了简化代码,您可以将整个内容提取到如下方法中:

    func outputGrandTotal(tipIndex: Int) {
        let billTotal = Double(subtotalText.text!)!
        let grandTotal = (billTotal * tipArray[tipIndex]) + billTotal
    
        //return grandTotal
        totalAmountLbl.text = String(format: "%.2f", grandTotal)
    }
    

    @IBAction func fiveBtn(_ sender: Any) {
        outputGrandTotal(tipIndex: 0)
    
    }
    
    @IBAction func tenBtn(_ sender: Any) {
        outputGrandTotal(tipIndex: 1)
    
    }
    
    @IBAction func fifteenBtn(_ sender: Any) {
        outputGrandTotal(tipIndex: 2)
    
    }
    
    @IBAction func twentyBtn(_ sender: Any) {
    
        outputGrandTotal(tipIndex: 3)
    
    }
    
    @IBAction func twentyfiveBtn(_ sender: Any) {
        outputGrandTotal(tipIndex: 4)
    }
    
    @IBAction func thirtyBtn(_ sender: Any) {
        outputGrandTotal(tipIndex: 5)
    
    }
    

    tag 你所有的按钮。那你只需要一个 @IBAction

    @IBAction func tipButtonTapped(_ sender: UIButton) {
        outputGrandTotal(tipIndex: sender.tag)
    }