我目前正在將我的iOS應用程序轉換爲Swift 2並且遇到此問題。我有一個使用數字鍵盤的文本字段。當我切換到Swift 2時,當我鍵入一個數字時,讓我們說5,它將在文本字段中顯示爲Optional("")5
。我很確定這是因爲某些擴展。UITextField在輸入之前顯示「可選(」「)」
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 – lagoon
突出顯示我們正在查看的部分。 –