簡體   English   中英

swift4中textfield的值為0時如何顯示提示?

[英]How to display alert when the value of textfield is 0 in swift4?

我想在textfield的值為0時顯示警報。但是,在textfield中輸入0的值不會顯示警報。

我該如何解決這個問題?

@IBOutlet var priceTextfield: UITextField!

if Int(priceTextfield.text!) == 0 {

   let aert = UIAlertController(title: "OK", message: "Price must be greater than 0.", preferredStyle: .alert)
   let ok = UIAlertAction(title: "OK", style: .default)
   alert.addAction(OK)

   self.present(alert, animated: false)
}

您應該處理的是textFieldShouldEndEditing委托。

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
    if Double(textField.text!) == 0 {
        // Show alert
        return false
    }
    return true
}

注意:您的視圖控制器需要符合UITextFieldDelegate並且必須設置文本字段委托。

class YourViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        priceTextfield.delegate = self
    }

}
   func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {

    if textField.text.count > 1 {
     if let value = Int(textField.text), value == 0 { // Convert string to Int
                    // Show alert
         }
       }

     return true
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM