【发布时间】:2016-01-29 21:48:45
【问题描述】:
我目前正在将我的 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
}
}
【问题讨论】:
-
发布您正在使用的代码
-
对不起,刚刚。 @ksa_coder
-
突出显示我们正在特别关注的部分。
-
它与newString有关,因为如果我将
textField.text = newString!更改为textField.text = 5,那么它应该可以正常工作。
标签: swift uitextfield swift2 optional