[英]How to add two numbers in Swift only when both of the text fields are filled in
I'm trying to add two numbers in Swift 5, and I want to add some error checks.我正在尝试在 Swift 5 中添加两个数字,并且我想添加一些错误检查。 I don't want to make it possible for a user to click on the plus button if both of the text fields are not filled in. I tried with the if state below but it did not work.
如果两个文本字段都没有填写,我不想让用户点击加号按钮。我尝试使用下面的 if 状态,但它不起作用。
the whole function:整个功能:
@IBAction func sum(_ sender: Any) {
let one = input1.text
let oneInt = Int(one!)
let two = input2.text
let twoInt = Int(two!)
let total = oneInt! + twoInt!
label.text = "\(total)"
if(input2.text == nil){
addBtn.isEnabled = false
}
if(input1.text == nil){
addBtn.isEnabled = false
}
}
try to use guard like this.If your input field does not contain any value that field return blank string and when you try to get integer value from that string it will return nil and your add button will be disable.尝试使用这样的保护。如果您的输入字段不包含任何值,该字段返回空白字符串,当您尝试从该字符串获取整数值时,它将返回 nil 并且您的添加按钮将被禁用。
@IBAction func sum(_ sender: Any) {
guard let text1 = input1.text, let intValue1 = Int(text1) else {
addBtn.isEnabled = false
return "error"
}
guard let text2 = input2.text, let intValue2 = Int(text2) else {
addBtn.isEnabled = false
return "error"
}
label.text = "\(intValue1 + intValue2)"
} }
A nice and simple way is to addTarget
to your textFiels
.一个很好的和简单的方法就是
addTarget
您textFiels
。 This will enable you to handle the events on the text field.这将使您能够处理文本字段上的事件。 In this scenario we'll use .editingChanged and use a single selector to achieve our goal:
在这种情况下,我们将使用.editingChanged并使用单个选择器来实现我们的目标:
What we'll do : We will listen for when someone types something in the textfield.我们将做什么:当有人在文本字段中输入内容时,我们会监听。 Whenever a text changed was made, we'll check to see if all the textfields was populated and then if it was we enable the sum button.
每当更改文本时,我们将检查是否填充了所有文本字段,然后启用 sum 按钮。
A small controller sample :: Make sure to read the comments to understand the code faster一个小控制器示例:: 请务必阅读注释以更快地理解代码
import UIKit
class ViewController: UIViewController {
@IBOutlet var textfield1: UITextField!
@IBOutlet var textfield2: UITextField!
@IBOutlet var sumButton: UIButton!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
sumButton.isEnabled = false /// Disable the button first thing
[textfield1, textfield2].forEach {
$0.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged) /// add targets to handle the events (in your case it listens for the 'editingChanged' event )
}
}
@objc func editingChanged(_ textField: UITextField) {
/// Here we just loop through all our textfields
for each in [textfield1, textfield2] {
if let text = each?.text { /// Just make sure the textfields text is not nil
if text.count < 1 {
// If the textfiels text has no value in, then we keep the button disabled and return
sumButton.isEnabled = false
return
}
} else {
/// Else if the text field's text is nill, then return and keep the button disabled
sumButton.isEnabled = false
return
}
}
sumButton.isEnabled = true /// If the code reaches this point, it means the textfields passed all out checks and the button can be enabled
}
@IBAction func sum(_ sender: Any) {
let one = textfield1.text!
let two = textfield2.text!
guard let oneInt = Int(one), let twoInt = Int(two) else {
print("Whatever was in that text fields, couldn't be converted to an Int")
label.text = "Be sure to add numbers."
return
}
let total = oneInt + twoInt
label.text = "\(total)"
}
}
textfields are not nil but empty strings.文本字段不是 nil 而是空字符串。 so make your comparison like :
所以让你的比较像:
if input1.text == "" {
// do your check here
}
Seems like you want to start with addBtn.isEnabled = false
then update it whenever the user enters two valid integers into the text fields, ie Int(input1.text ?? "") != nil && Int(input2.text ?? "") != nil
.似乎您想从
addBtn.isEnabled = false
开始,然后在用户在文本字段中输入两个有效整数时更新它,即Int(input1.text ?? "") != nil && Int(input2.text ?? "") != nil
。 You can do this by adding a target to your textfields ( input1
and input2
) for .editingChanged
events.您可以通过为
.editingChanged
事件向文本字段( input1
和input2
)添加目标来实现此目的。 For example, if you're doing this in a UIViewController
, you can do this in viewDidLoad
:例如,如果您在
UIViewController
中执行此操作,则可以在viewDidLoad
执行此操作:
override func viewDidLoad() {
super.viewDidLoad()
addBtn.isEnabled = false
input1.addTarget(self, action: #selector(textFieldDidEdit(_:)), for: .editingChanged)
input2.addTarget(self, action: #selector(textFieldDidEdit(_:)), for: .editingChanged)
}
Where textFieldDidEdit(_:)
action looks like:其中
textFieldDidEdit(_:)
操作如下所示:
@objc func textFieldDidEdit(_ sender: UITextField) {
addBtn.isEnabled = Int(input1.text ?? "") != nil && Int(input2.text ?? "") != nil
}
Finally your sum
function becomes:最后你的
sum
函数变成:
@IBAction func sum(_ sender: UIButton) {
guard let oneInt = Int(input1.text ?? ""), let twoInt = Int(input2.text ?? "") else {
return
}
let total = oneInt + twoInt
label.text = "\(total)"
}
As all of the number validation has moved to the textFieldDidEdit(_:)
function.由于所有数字验证都已转移到
textFieldDidEdit(_:)
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.