在UITextField中输入文本占位符时,应该在一个字母处消失

时间:2017-01-30 14:36:54

标签: ios swift uitextfield placeholder

我创建了一个UITextfield我要添加4位数的密码,但是一旦我输入第一个数字,整个占位符就会消失。在输入下一个密码字母时,如何在UITextfield中保留下三个占位符字母。

这是我的截图:

enter image description here

3 个答案:

答案 0 :(得分:1)

不要使用placeHolder,只需覆盖shouldChangeCharactersInRange方法并将字符附加到字符串,直到字符串长度为4个字符,如果需要{{1},也可以使用属性字符串看起来与点不同。

答案 1 :(得分:1)

我想尝试SeanLintern88的解决方案,因为它听起来有点像挑战。并且在文本字段应该在下划线之间有空格的情况下。

textField.text = "_ _ _ _"

这是我带来的解决方案,虽然编写很有趣,但我不推荐在实际项目中使用。最好尝试4个单独的文本字段方法:)

extension ViewController: UITextFieldDelegate {

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

        guard let text = textField.text else { return false }

        var location = range.location

        //is deleting
        if string == "" {

            guard let indexToReplace = text.index(text.startIndex, offsetBy: location, limitedBy: text.endIndex) else {
                return false
            }

            let isCharDeleted = location % 2 == 0
            //place " " or "_" depending on the position that was deleted
            let stringToReplaceWith = isCharDeleted ? "_" : " "
            let charachter = stringToReplaceWith[stringToReplaceWith.startIndex]
            textField.text?.remove(at: indexToReplace)
            textField.text?.insert(charachter, at: indexToReplace)

            var newCursorPositionOffset = location

            //deletetion occured on space " "
            if !isCharDeleted {

                guard let previousIndex = text.index(text.startIndex, offsetBy: location-1, limitedBy: text.endIndex) else {
                    return false
                }
                //delete the previous charachter
                textField.text?.remove(at: previousIndex)
                let dash = "_"
                let char = dash[dash.startIndex]

                textField.text?.insert(char, at: previousIndex)

                //correct cursor position
                newCursorPositionOffset -= 1
            }

            //move cursor position
            let newPosition = textField.position(from: textField.beginningOfDocument, offset: newCursorPositionOffset)
            textField.selectedTextRange = textField.textRange(from: newPosition!, to: newPosition!)

            return false
        }

        //is typing
        if range.location + 1 <= text.characters.count,
            let end = text.index(text.startIndex, offsetBy: location+1, limitedBy: text.endIndex),
            let start = text.index(text.startIndex, offsetBy: location, limitedBy: text.endIndex) {
            textField.text = textField.text?.replacingOccurrences(of: "_", with: string, options: .caseInsensitive, range: Range(uncheckedBounds: (lower: start, upper: end)))

            //correct the cursor position if placed on " " index
            if range.location % 2 != 0 {
                location -= 1
            }
        }

        //skip " " and move cursor to the next "_"
        if location+2 < text.characters.count {
            let newPosition = textField.position(from: textField.beginningOfDocument, offset: location+2)
            textField.selectedTextRange = textField.textRange(from: newPosition!, to: newPosition!)

        }

        return false
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        let newPosition = textField.beginningOfDocument
        textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)


    }
}
PS:可能通过更好地选择字符串操作的功能可以缩短它,但仍然是一个非常不友好的解决方案。

结论:不要在家做这件事:D

答案 2 :(得分:0)

Swift 4

这是@Denislava Shentova的答案的修改版本,我相信它可以简化为更少的代码行,修复问题并使代码更具可读性。

未完全测试

import UIKit

class YourClass: UIViewController {

    //It is also a good idea to deny users the ability to paste into this textField.

    //set up textField
    let textField : UITextField = {
        let textField = UITextField()
        // These are 'long dashes' you can replace them with whatever you would like.
        // These look best IMO.
        textField.text = "——————" //No spaces needed!
        textField.textColor = .black
        textField.textAlignment = .center
        textField.tintColor = .clear //this will hide the cursor.

        return textField
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
        //This sets the spacing or 'Kern' of the textfield. Adjust the value: 10.0 and the fontSize to get the desired output.
        textField.defaultTextAttributes.updateValue(10.0, forKey: NSAttributedStringKey.kern.rawValue)
    }
}
extension YourClass : UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        //get the current text of the textField.
        guard let text = textField.text else { return false }

        //handle backspace event.
        if string == "" {
            guard let indexToReplace = text.index(text.startIndex, offsetBy: range.location, limitedBy: text.endIndex) else { return false }
            textField.text?.remove(at: indexToReplace)
            textField.text?.insert("—", at: indexToReplace)
            //adjust cursor position
            if let newPostion = textField.position(from: textField.beginningOfDocument, offset: range.location) {
                textField.selectedTextRange = textField.textRange(from: newPostion, to: newPostion)
                return false
            }
        }
        //handle character entered event.
        if range.location + 1 <= text.count,
            let end = text.index(text.startIndex, offsetBy: range.location + 1, limitedBy: text.endIndex),
            let start = text.index(text.startIndex, offsetBy: range.location, limitedBy: text.endIndex) {
            textField.text = textField.text?.replacingOccurrences(of: "—", with: string, options: .caseInsensitive, range: Range(uncheckedBounds: (lower: start, upper: end)))
        }
        //adjust cursor position.
        if range.location + 1 < text.count {
            if let newPosition = textField.position(from: textField.beginningOfDocument, offset: range.location + 1){
                textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
            }
        }
        return false
    }
    //make sure to start at the begining of the textField.
    func textFieldDidBeginEditing(_ textField: UITextField) {
        let newPosition = textField.beginningOfDocument
        textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
    }
}