ios - 如何在 UItextfield 中快速添加永久占位符?

标签 ios swift uitextfield

我试图让文本字段在用户开始输入时始终以“@gmail.com”结尾。因此,在对文本字段进行任何更改后,它总是会将该行附加到用户已经键入的任何内容,并且用户不应该能够删除它。

我尝试过使用“shouldChangeCharactersIn”函数,但似乎无法正常工作。

我这样做的原因是用户可以理解我们只接受 gmail 帐户,并认为这是最好的方法,而不是试图解析字符串的最后 10 个字符来检查“@gmail” .com”。

最佳答案

你应该这样做:

enter image description here

如果用户添加 @ 然后拒绝该部分,则可以控制:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 0 {
        if string == "@" {
            return false
        }
    }
    return true
}

所以您基本上显示标签是 @gmail.com 并且用户在 textField 中添加第一部分。

更新:
如果你真的想在 textField 中使用它:

func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = textField.text! + "@gmail.com"

        textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument)
    }

这里分两部分:
1: textField.text = textField.text! + "@gmail.com" - 将@gmail.com 添加到您的字符串

2: textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument) - 当用户点击 textField 时将光标放在开头。

关于ios - 如何在 UItextfield 中快速添加永久占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843825/

相关文章:

ios - 当 UISlider 一直拖到最后时会触发什么事件?

ios - 从 Parse 中的指针列获取数据(iOS)

ios - 使用导航 Controller 后选项卡栏项目图标丢失

swift - 如何在swift中从另一个函数访问函数参数

ios - 如何使用 keepLayout 使 UITextField 中的光标从边缘开始一个空格?

ios - Xamarin Prism 形式 : Application windows are expected to have a root view controller at the end of application launch

ios - 从 iOS 模拟器截屏并在 App Store Connect 中使用

swift - Alamofire 协议(protocol)返回模型对象数组

ios - 有没有办法在您输入时更改文本字段内文本的颜色?

iphone - 为电话号码文本字段设置适当的键盘