![](/img/trans.png)
[英]How to display the value of a key when user enters the key in textField in swift
[英]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.