Swift : textFieldShouldBeginEditing 函数修复
Swift : textFieldShouldBeginEditing function fix
下面的代码删除了 inputField 中的最后一个字符,当我使用默认值时它工作得很好。但是,如果文本字段为空,则会出现错误,因为没有要删除的最后一个字符。
如何用if else
查询?
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
textField.text?.removeLast()
percentageField.text = textField.text
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
您可以通过以下方式进行:
if (!textField?.text?.isEmpty) {
textField.text?.removeLast()
}
所以只有当 textField 为空时才删除 Last
removeLast
必须用于非空字符串,因此请确保它不为空:
if let text = textField.text, !text.isEmpty {
textField.text?.removeLast()
}
您可以在执行前检查文本框中是否有任何值 textField.text?.removeLast()
。
您可以将代码更改为
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if (!textField.text == "") {
textField.text?.removeLast()
percentageField.text = textField.text
}
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
您可以使用:
if !(textField.text!.isEmpty) {
textField.text?.removeLast()
}
更多细节请参考苹果文档:
下面的代码删除了 inputField 中的最后一个字符,当我使用默认值时它工作得很好。但是,如果文本字段为空,则会出现错误,因为没有要删除的最后一个字符。
如何用if else
查询?
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
textField.text?.removeLast()
percentageField.text = textField.text
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
您可以通过以下方式进行:
if (!textField?.text?.isEmpty) {
textField.text?.removeLast()
}
所以只有当 textField 为空时才删除 Last
removeLast
必须用于非空字符串,因此请确保它不为空:
if let text = textField.text, !text.isEmpty {
textField.text?.removeLast()
}
您可以在执行前检查文本框中是否有任何值 textField.text?.removeLast()
。
您可以将代码更改为
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if (!textField.text == "") {
textField.text?.removeLast()
percentageField.text = textField.text
}
return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}
您可以使用:
if !(textField.text!.isEmpty) {
textField.text?.removeLast()
}
更多细节请参考苹果文档: