如何在用户输入时将uitextfield中的光标移动到第二个字符

时间:2017-08-02 08:56:51

标签: ios swift uitextfield

我想让用户无法删除第一个字符或插入新的第一个字符,以及当用户尝试插入新的第一个字符以将光标移动到第二个字符时。

我已经通过以下方式实现了第一部分。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if (range.length == 1 && range.location == 0 && string == ""){
            return false
        }
        if (range.length == 0 && range.location == 0 && string != ""){
            return false
        }
    return true
}

但是这会导致用户卡在第一个无法输入任何内容的角色上,除非他们自己移动指针。

如何实现将光标移动到第二个字符位置的第二部分,以便用户可以从第二个字符开始输入?

2 个答案:

答案 0 :(得分:0)

let newPosition = textField.endOfDocument;
self.yourtextFieldName.selectedTextRange = textField.textRange(from: newPosition, to: newPosition);

答案 1 :(得分:0)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let text = textField.text {
        if range.location == 0 && range.length == 1 {
            return false
        }
        if range.location == 0 && text.characters.count > 0 {
            let position = textField.position(from: textField.beginningOfDocument, offset: 1)!
            textField.selectedTextRange = textField.textRange(from: position, to: position)
        }
    }
    return true
}