【问题标题】:Passing value of a textfield to a label in swift将文本字段的值快速传递给标签
【发布时间】:2017-09-23 10:49:21
【问题描述】:
我有一个文本字段,我希望它在按下按钮时隐藏和显示,我还希望将文本字段中的文本传递给文本字段下方的标签。我试过这个:
@IBAction func myfunction(_ sender: UIButton) {
if textfield.isHidden == true{
textfield.isHidden = false
}else{
label.text = textfield.text
textfield.isHidden = true
}
}
显然隐藏和显示部分正在工作,但行
label.text = textfield.text
不是。我收到类似“Thread 1: EXC_BREAKPOINT (code=1, subcode=0x10143fb50”) 的错误,在控制台中出现“致命错误:在展开可选值时意外发现 nil”
谁能帮帮我。
【问题讨论】:
标签:
swift
label
textfield
optional
【解决方案1】:
根据您的错误,您似乎尝试使用这一行 label.text = textfield.text 将文本字段中的文本转换为标签,但问题是您的 textfield.text 为零。
这就是为什么你有错误unexpectedly found nil while unwrapping an Optional value
您的文本字段是可选的。它可以有一个值或 nil。如果您尝试解开具有 nil 的可选值,则会出现这种错误。
这里的解决方案是像这样使用 Optional Binding 安全地解开可选值:
if let textInput = textfield.text {
//There is a text in your textfield so we get it and put it on the label
label.text = textInput
} else {
//textfield is nil so we can't put it on the label
print("textfield is nil")
}
【解决方案2】:
这是一个您可以尝试的更简单的代码。零合并运算符 (a ?? b) 展开可选的 a。如果它包含一个值,或者如果 a 为 nil,则返回一个默认值 b。
@IBAction func myfunction(_ sender: UIButton) {
label.text = textfield.text ?? ""
}