![](/img/trans.png)
[英]Swift 3, accessing user input Text Field values from ViewControler and used them in a model .swift file
[英]Loop user input from text boxes in Swift
我的iOS待辦事項應用程序中有兩個文本框,一個用於任務名稱,另一個用於描述。 當用戶將一個或兩個文本框留為空白時,我要向用戶發出有關該問題的警報,並將其循環播放,直到兩個文本框不再為空白為止。 這是我的代碼:
var validInput :Bool = false //for while
while (validInput == false) {
if (txtTask.text == "" || txtDesc.text == "") {
var alert = UIAlertController(title: "Error", message: "Task and description cannot be blank", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
validInput == true
}
}
該代碼位於@IBAction
函數中,該函數在用戶按下Done
時運行。 我的代碼在無限循環中運行,原因很明顯。 我如何實現自己想要的?
我有個主意:
Done
時再次運行該功能。 我如何a)將上面的代碼放入代碼中,或b)正確使用上面的循環?
答案是: 不要這樣做!
您不需要循環textField來觀察值的變化。 正確的方法是使用UITextField的委托方法,例如
- textFieldDidBeginEditing:
了解用戶何時開始編輯,
- textField:shouldChangeCharactersInRange:replacementString:
當textField文本值更改時
- textFieldDidEndEditing:
知道用戶何時結束編輯
等等...
如文檔所述:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/
在這種情況下,使用循環執行此類操作是一種不好的做法。 (並且您將不得不做很多事情才能不阻止當前線程,驗證屏幕上是否已經有警報等)
如果您在“完成”按鈕中使用了while
循環,則它將陷入您所說的無限循環中。 因此,用戶沒有機會進行任何更改。
相反,您應該使用if
語句來檢查那些框是否為空,並向它們發出警告,而不執行任何操作。
if condition {
// Execute your code if both boxes are filled
} else {
// Show alert
}
如果您堅持使用while循環,則必須讓用戶在警報中輸入文本。 然后您的代碼將起作用。
這里不需要while循環。 只需在if else循環中執行此操作,因為在提交文本或將其保留為空后每次按下“ Done
按鈕,都會執行您的代碼段。
if (txtTask.text == "" || txtDesc.text == "") {
var alert = UIAlertController(title: "Error", message: "Task and description cannot be blank", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
//Do something or print.
}
我假設這段代碼在@IBAction
方法中。
把事情簡單化:
@IBOutlet var textA: UITextField!
@IBOutlet var textB: UITextField!
@IBAction func validateButton(sender: AnyObject) {
if (textA.text == "" || textB.text == "") {
println("ALERT: BLANK FIELDS")
} else {
println("Let's run some code since we're not blank")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.