如何实现占位符文本在UITextField中逐个字符消失 [英] How to achieve that placeholder text disappears character by character in UITextField

查看:151
本文介绍了如何实现占位符文本在UITextField中逐个字符消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮帮我。

UITextField 当我们提供占位符文本时,其占位符字符串将是当我们输入任何角色时就消失了我怎样才能实现只输入的字符不会是完整的字符串?这意味着,如果我输入3个字符,则只占位符的前3个字符。

In UITextField when we provide a placeholder text its placeholder string will be gone when we enter any character. How can I achieve that only entered character will be gone not a full string? Meaning that if I type in 3 characters, only the first 3 characters of placeholder will be gone.

#EDIT 1

此外,新输入的字符文字颜色将会改变,其他字符文字也会改变颜色保持不变。

Also, newly entered character text color will change and other remaining character text color remains same.

提前致谢。

推荐答案

我不喜欢不相信占位符的默认行为是可编辑的,但您尝试完成的操作可以使用 NSAttributedString 来模拟占位符值。

I don't believe the default behavior of the placeholder is editable, but what you are trying to accomplish can be done using NSAttributedString to simulate the placeholder value.

我确信这可以优化,但在这里我创建了一个处理程序类,它充当给定 UITextField 的委托,操纵字符串用户输入以实现所需的效果。使用所需的占位符字符串初始化处理程序,这样就可以使任何文本字段以这种方式工作。

I'm sure this can be optimized, but here I have created a handler class that acts as the delegate for a given UITextField, manipulating the string the user inputs to achieve the desired effect. You init the handler with your desired placeholder string, so you can make any text field work this way.

import UIKit

class CustomPlaceholderTextFieldHandler: NSObject {
    let placeholderText: String
    let placeholderAttributes = [NSForegroundColorAttributeName : UIColor.lightGray]
    let inputAttributes = [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 153/255, blue: 0, alpha: 1.0)]
    var input = ""

    init(placeholder: String) {
        self.placeholderText = placeholder
        super.init()
    }

    func resetPlaceholder(for textField: UITextField) {
        input = ""
        setCombinedText(for: textField)
    }

    fileprivate func setCursorPosition(for textField: UITextField) {
        guard let cursorPosition = textField.position(from: textField.beginningOfDocument, offset: input.characters.count)
            else { return }

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

    fileprivate func setCombinedText(for textField: UITextField) {
        let placeholderSubstring = placeholderText.substring(from: input.endIndex)
        let attributedString = NSMutableAttributedString(string: input + placeholderSubstring, attributes: placeholderAttributes)
        attributedString.addAttributes(inputAttributes, range: NSMakeRange(0, input.characters.count))
        textField.attributedText = attributedString
    }
}

extension CustomPlaceholderTextFieldHandler: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if string == "" {
            if input.characters.count > 0 {
                input = input.substring(to: input.index(before: input.endIndex))
            }
        } else {
            input += string
        }

        if input.characters.count <= placeholderText.characters.count {
            setCombinedText(for: textField)
            setCursorPosition(for: textField)
            return false
        }
        return true
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        setCursorPosition(for: textField)
    }
}

这是我初始化上面的gif的方式:

Here's a the way I initialized the gif above:

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    let placeholderHandler = CustomPlaceholderTextFieldHandler(placeholder: "_2_-__-__A")

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = placeholderHandler
        placeholderHandler.resetPlaceholder(for: textField)
    }
}

这可以扩展为在初始化时获取颜色参数,字体等,或者您可能会发现它更清晰,可以继承 UITextField 并使其成为自己的委托。我还没有真正测试这个选择/删除/替换多个字符。

This could be expanded to take color parameters, fonts, etc. at initialization, or you may find it cleaner to subclass UITextField and make it its own delegate. I also haven't really tested this for selecting/deleting/replacing multiple characters.

输入变量将返回用户在任何给定点输入的文本。此外,使用固定宽度字体可以消除用户键入和替换占位符文本时的抖动。

The input variable will return the text the user has input at any given point. Also, using a fixed-width font would remove the jitteriness as the user types and replaces the placeholder text.

这篇关于如何实现占位符文本在UITextField中逐个字符消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆