gpt4 book ai didi

swift - UITextField 在输入之前显示 "Optional("")"

转载 作者:行者123 更新时间:2023-11-30 10:07:48 24 4
gpt4 key购买 nike

我目前正在将我的 iOS 应用程序转换为 Swift 2,并遇到了这个问题。我有一个使用数字键盘的文本字段。当我切换到 Swift 2 时,当我输入数字(比如 5)时,它将在文本字段中显示为 Optional("")5。我很确定这是因为扩展中的某些内容。

extension GroupViewController: UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var shouldProcess = false
var shouldMoveToNextField = false

let insertStringLength = string.characters.count
if insertStringLength == 0 {
shouldProcess = true
} else {
if textField.text!.characters.count == 0 {
shouldProcess = true
}
}

if shouldProcess {
var newString = textField.text

if newString!.characters.count == 0 {
newString = "\(newString)\(string)"
shouldMoveToNextField = true
} else {
if insertStringLength > 0 {
newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
} else {
newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: "")
}
}

textField.text = newString!

if shouldMoveToNextField {
let nextResponder = textField.superview?.viewWithTag(textField.tag + 1)

if let nextResponder = nextResponder {
nextResponder.becomeFirstResponder()
} else {
dismissKeyboard()
}
}
}
return false
}
}

最佳答案

在下面的代码中:

 var newString = textField.text

if newString!.characters.count == 0 {
newString = "\(newString)\(string)"
shouldMoveToNextField = true
}

改变...

newString = "\(newString)\(string)"

到...

newString = "\(string)"

关于swift - UITextField 在输入之前显示 "Optional("")",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35094638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com