UITextField

时间:2016-10-25 07:01:24

标签: ios swift uiviewcontroller uitextfield viewcontroller

ViewController由两个名为textName&的TextField组成。 textEmail。 View Controller使用textName加载光标。 textName包含预先填充的单词“@ gmail.com”。

在从textName点击键盘的返回键时,焦点移动到Textfield textEmail。默认情况下,光标位于单词“@ gmail.com”

之后

我想把光标放在开头。即@ gmail.com之前

这是我的代码。当我从textName点击返回键时,光标将转到textEmail的开头。但是当我直接点击textEmail时,光标会出现在预先填充的单词之后。请帮我!

func textFieldShouldReturn(textField: UITextField) -> Bool {

        if textField == self.textName{
            textEmail.becomeFirstResponder()
            let desiredPosition = textEmail.beginningOfDocument
            textEmail.selectedTextRange = textEmail.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)
        }

        if textField == self.textEmail{


            dismissViewControllerAnimated(true, completion: nil)

        }

        return true
    }

作为一个注释,我确实尝试编辑textEmail的开始动作并添加到代码下面,但它也没有用。

let desiredPosition = textEmail.beginningOfDocument
            textEmail.selectedTextRange = textEmail.textRangeFromPosition(desiredPosition, toPosition: desiredPosition)

2 个答案:

答案 0 :(得分:2)

请改为尝试:

func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == self.textName{
        let beginning = textField.beginningOfDocument
        textField.selectedTextRange = textField.textRange(from: beginning, to: beginning)
    }
}

请删除textEmail.becomeFirstResponder()并使用textField.textRange代替textEmail.textRangeFromPosition

textFieldDidBeginEditing函数内部使用参数textField,如上例所示。

答案 1 :(得分:0)

首先设置委托UITextFieldDelegate

TextField委托后,在viewDidLoad中设置Self

示例

textName.delegate = self 
textEmail.delegate = self

然后在viewController中复制此方法

 func textFieldShouldReturn(textField: UITextField) -> Bool
    {
        if textField == textName
        {
            textName.resignFirstResponder()
            textEmail.becomeFirstResponder()
             textEmail.text = "@gmail.com"
            let newPosition = textField.beginningOfDocument
           textEmail.selectedTextRange = textEmail.textRangeFromPosition(newPosition, toPosition: newPosition)



        }
        else if textField == textEmail
        {
            textEmail.resignFirstResponder()
        }
        return true
    }