2017-07-15 54 views
1

我正在教我自己,快一個星期半左右。我正在試圖製造一個從英寸到釐米的轉換器。我有兩個文本框,一個用英寸打一個,一個用釐米打。當您在其中鍵入其中一個時,您可以點擊計算,它會爲您提供英寸或釐米的轉換。我遇到的問題是,如果你填寫一個,然後你決定寧願看到另一個度量單位,那麼這些數字仍然是輸入的,而且按鈕不起作用。如果用戶決定使用其他字段,我如何清除文本字段?在第二個字段中輸入時使第二個文本字段清晰的Swift代碼

也不知道是否有可能與我上傳的代碼,但我寧願擺脫轉換按鈕都在一起,所以當用戶鍵入單位或其他立即填寫標籤下面。這可能嗎?

這是目前爲止的代碼。

import UIKit 

class ViewController: UIViewController, UITextViewDelegate{ 

    @IBOutlet weak var InchesField: UITextField! 
    @IBOutlet weak var CentimetersField: UITextField! 
    @IBOutlet weak var ConversionLabel: UILabel! 

    //Only let 1 decimal point 
    let numberFormatter: NumberFormatter = { 
     let nf = NumberFormatter() 
     nf.numberStyle = .decimal 
     nf.minimumFractionDigits = 0 
     nf.maximumFractionDigits = 1 
     return nf 
    }() 

    @IBAction func ConversionButton1(_ sender: AnyObject) { 

    if InchesField.text == "" || CentimetersField.text == "" { 
     //either inchfield or centimetersfield text is empty 
     ConversionLabel.text = String("Please enter a number") 
    } 

    if let text = InchesField.text, !text.isEmpty 
     { 
      //do something if it's not empty 
      let inch = Double(InchesField.text!) 
      let inCmConvertor = inch! * 2.54 

      ConversionLabel.text = String("\(inCmConvertor) Centimters") 
    } else 
    if let text = CentimetersField.text, !text.isEmpty 
    { 
      let centimeter = Double(CentimetersField.text!) 
      let cmInConvertor = centimeter!/2.54 

     ConversionLabel.text = String("\(cmInConvertor) Inches") 
    } 

    } 
} 

Heres a screenshot

回答

1

你想要做的是與編輯每個文本字段在IBAction爲創建窗口中更改事件創建一個IBAction爲。

我測試下面的代碼和它的工作:

@IBOutlet weak var InchesField: UITextField! 
@IBOutlet weak var CentimetersField: UITextField! 

@IBAction func InchesFieldChanged(_ sender: Any) { 
CentimetersField.text = "" 
} 

@IBAction func CentimetersFieldChanged(_ sender: Any) { 
    InchesField.text = "" 
} 

不要複製和粘貼代碼,只需手動創建IBActions,它會簡單得多。

祝你的旅程順利進入Swift編程和iOS開發。

+0

好的,非常感謝您的快速回復!我從故事板到控制器的藥物,並做出如上所述的動作func,但是當我完成時,我得到錯誤 無法指定'string'類型的值來鍵入'UITextField!'。 –

+0

沒關係我錯過了那個我的錯誤的文字部分 –

+0

現在如果我想要拿走角色呢。如果有人不小心碰到一個角色,它會使程序崩潰。我知道這與NSRange或者沿着這些線的東西有關 –

相關問題