[英]Check if if a text field from a collection of UITextFields is empty
I currently have a collection of UITextFields wired from IB to my Swift code. 我目前有一系列UITextFields从IB连接到我的Swift代码。 The user has option to tap a button to proceed to the next view, but my app requires all fields to be filled.
用户可以选择点击按钮进入下一个视图,但我的应用程序需要填写所有字段。 Below is my method that checks if a text field is empty:
下面是检查文本字段是否为空的方法:
func findEmptyField() -> UITextField? {
for field in fieldsCollection {
if field.text.isEmpty {
return field
}
}
//Return here a value signifying that no fields are empty.
}
This method is only partially implemented, as I'm not sure how & what to return if none of them are empty. 这个方法只是部分实现,因为我不知道如果它们都不为空,如何返回以及返回什么。 The caller of this function checks the return value and performs an action dependent on whether it returns a field or not.
此函数的调用者检查返回值并根据它是否返回字段执行操作。 I vaguely understand that the optionals feature of Swift can help with this, but I'm not certain how.
我模糊地理解Swift的选项功能可以帮助解决这个问题,但我不确定如何。
What should I make the fn return so that the caller recognizes that none of the fields from the collection are empty? 我应该如何使fn返回,以便调用者识别出集合中的所有字段都不为空?
You've set it up perfectly -- since you're already returning an optional UITextField?
你已经完美地设置了 - 因为你已经返回了一个可选的
UITextField?
, if there aren't any empty text fields, return nil
: ,如果没有任何空文本字段,则返回
nil
:
func findEmptyField() -> UITextField? {
for field in fieldsCollection {
if field.text.isEmpty {
return field
}
}
return nil
}
When calling it, note that you'll get an optional value back. 在调用它时,请注意您将获得一个可选值。 Unwrap it with optional binding:
用可选绑定打开它:
if let emptyField = findEmptyField() {
// focus emptyField or give a message
} else {
// all fields filled, ok to continue
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.