2016-09-23 56 views
0

我想在我的應用程序中有一個場景,允許用戶在兩​​個單獨的文本字段中輸入數字,它會執行一些基本的數學運算,並在點擊時將輸出吐出到標籤中「計算按鈕」。我觀看過視頻,更改了代碼,我似乎無法按照自己的意願工作,而且我的應用一直在崩潰。這是我迄今爲止的簡單代碼。任何人都可以解釋我輸入什麼是錯誤的,我需要改變什麼?非常感謝,謝謝!簡單文本字段來更改標籤答案

import UIKit 

class DopamineCalculator: UIViewController { 

//Patient weight Input 

@IBOutlet weak var patientWeight: UITextField! 


//calculate button 
@IBAction func calculateButton(sender: AnyObject) { 

    let weightPatient = Double(self.patientWeight.text!) 

    dripAnswer.text = String(weightPatient * 2) 

} 


//Clear button action 
@IBAction func clearButton(sender: AnyObject) { 
    self.patientWeight.text=nil 
    //self.dosageDesired.text=nil 
    self.dripAnswer.text=nil 
} 


//Drip Rate Answer Label 
@IBOutlet weak var dripAnswer: UILabel! 

我的「清除」按鈕有效,但我無法使「計算」按鈕正常工作。我現在試圖保持簡單,只需添加兩個框,但我甚至無法讓它工作。

+0

什麼崩潰你得到? – Paulw11

+0

這是一個很長的名單,但基本上單打我的「calculatebutton」按鈕作爲原因 – beans217

+0

這不是原因。特定的行會有特定的例外。 – Paulw11

回答

0
var weightpatient = Double(self.patientweight.text!) 
    weightpatient = Double(weightpatient!*2) 
    let basicStr:String = String(format:"%f", weightpatient!) 
    dripanswer.text = String(basicStr) 

做工精細..

這裏是演示鏈接https://www.dropbox.com/s/p67f88qnnsekivn/Blur.zip?dl=0嘗試,讓我知道

+0

由於某些原因,它仍然崩潰。我複製了您在IBaction下輸入的內容。我有可能鏈接錯了什麼? – beans217

+0

更新了答案 – gurmandeep

+0

「2016-09-22 23:14:05.082 FCEMS協議[1193:351411] ***由於未捕獲異常'NSUnknownKeyException',原因:'[ setValue:forUndefinedKey: ]:這個類不是關鍵計算按鈕編碼兼容的關鍵值 – beans217

0

也許一個 「!」在重量患者之後。子代碼在我的模擬器(xcode 7.3.1)上很好。

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var patientweight: UITextField! 

    @IBAction func calculatebutton(sender: AnyObject) { 
    let weightpatient = Double(self.patientweight.text!) 

    dripanswer.text = String(weightpatient! * 2) 

    } 

    @IBAction func clearbutton(sender: AnyObject) { 
    self.patientweight.text=nil 
    //self.dosagedesired.text=nil 
    self.dripanswer.text=nil 
    } 

    @IBOutlet weak var dripanswer: UILabel! 

    override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    } 
} 
0

首先,你應該檢查輸入的病人體重是否是一個數字。使用這個擴展:

extension String { 
var isNumber: Bool 
{ 
    let range = self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) 
    return (range == nil) 
} 
} 

然後你檢查字符串不是空的,它包含一個數字,如果符合這些條件2你繼續計算..

@IBAction func calculateButton(sender: AnyObject) { 
    if patientWeight.text != "" && patientWeight.isNumber==true{ 
    let weightPatient = Double(self.patientWeight.text!) 
    self.dripAnswer.text = String(weightPatient! * 2) 
    } 
    else{ 
    self.dripAnswer.text = "Please enter weight" 
    } 
}