2016-02-22 18 views
0

(編程在迅速2)強制的UITextField爲小寫打字時和保持光標位置

我有一個的UITextField當用戶鍵入到它應該是自動轉換爲小寫打字時(因此不是後表單驗證)。

我已經此遠得到:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    //only convert to lowercase for username field 
    if textField == textFieldUsername { 
     //let stringRange = NSRange(location: range.location, length: range.length) 
     let completedString = (textField.text ?? "" as NSString).stringByReplacingCharactersInRange(range, withString: string) 
     //convert the while thing to lowercase and assign back to the textfield 
     textField.text = completedString.lowercaseString 
     //return false to indicate that the "system" itself should not do anychanges anymore, as we did them 
     return false 
    } 
    //return to the "system" that it can do the changes itself 
    return true 
} 

問題是,(1)當用戶按下並保持在的UITextField到(2)中途某處將光標移動到該字符串和(3)開始內鍵入(4)光標跳回到已經輸入的字符串的末尾。

是否需要在textField之後恢復光標位置:shouldChangeCharactersInRange被調用可能嗎?

+0

也許這篇文章可以幫助http://stackoverflow.com/questions/33195946/force-lowercase-ios-swift – bhmahler

+0

NOP,這與光標的問題.... – HixField

+0

這不是遊標問題。這可以改進。參考: [鏈接] http://stackoverflow.com/questions/4180263/moving-the-cursor-to-the-beginning-of-uitextfield – UIResponder

回答

3

我採取了你的代碼,並試過這個。

我可以在文本改變的地方替換光標位置。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 

    let start = textField.positionFromPosition(textField.beginningOfDocument, offset:range.location) 

    let cursorOffset = textField.offsetFromPosition(textField.beginningOfDocument, toPosition:start!) + string.characters.count 


    textField.text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string).lowercaseString 

    let newCursorPosition = textField.positionFromPosition(textField.beginningOfDocument, offset:cursorOffset) 

    let newSelectedRange = textField.textRangeFromPosition(newCursorPosition!, toPosition:newCursorPosition!) 

    textField.selectedTextRange = newSelectedRange 

    return false 
} 
+0

完美的作品! – HixField

+0

雖然最簡單的方法就像@Pradeep K提到的那樣,但我已經改進了您的代碼,因爲您已經擁有了它。 正如Pradeep K提到的那樣 – UIResponder

+0

在shouldChangeCharactersInRange委託回調中更改文本不是一個好習慣。取決於你正在嘗試做什麼,你會得到意想不到的結果。這個委託只能用來檢查範圍內的字符是否可以更改。但實際文本應該在UITextFieldDidChangeNotification中進行更改。 –

1

更簡單的方法是這樣的。

  1. 註冊爲UITextFieldTextDidChangeNotification

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidChange:", name: UITextFieldTextDidChangeNotification, object: textField)

  2. 更改通知回調的情況。

    func textFieldDidChange(notification:NSNotification) { textField.text = textField.text?.lowercaseString }

+0

最佳解決方案。謝謝! – UIResponder

相關問題