Swift中的UITextfield字符数限制

时间:2016-07-27 03:45:38

标签: swift uitextfield

在文本字段中,我只想允许16个字符。我不想允许输入超过16个字符。这是我的代码;

let currentCharacterCount = txtPinNo.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= 19

我的预期结果是 - &gt; 1234-1111-3333-6666 (19个字符)
我的实际结果结果是 - &gt; 1234-1111-2222-4444- 4 (最后一个数字总是出现,只想删除“-4”)

我不想在超过16个字符时输入。请帮我检查一下。

1 个答案:

答案 0 :(得分:1)

您可以继承UITextField并创建自定义字段,如下所示:

@IBDesignable
class LimitedLengthField: UITextField {
    @IBInspectable var maxLength: Int = 16 // set maximum number of characters
    var stringValue: String { return text ?? "" }
    override func awakeFromNib() {
        super.awakeFromNib()
        keyboardType = .ASCIICapable   // set the keyboard type
        addTarget(self, action: #selector(editingChanged), forControlEvents: .EditingChanged)
        editingChanged(self)
    }
    func editingChanged(sender: UITextField) {
        sender.text = String(stringValue.characters.prefix(maxLength))
    }
}

如果你需要广告一些自定义格式,它会变得有点但更棘手:

Swift 2

class CustomField: UITextField {
    var stringValue: String { return text ?? "" }
    var decimalDigits: String {
        return stringValue
            .componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
            .joinWithSeparator("") ?? ""
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        addTarget(self, action: #selector(editindChanged(_:)), forControlEvents: .EditingChanged)
        keyboardType = .NumberPad
        editindChanged(self)
    }
    func editindChanged(sender: UITextField) {
        let letters = Array(decimalDigits.stringByPaddingToLength(16, withString: " ", startingAtIndex: 0).characters)
        switch decimalDigits.characters.count {
        case 1...4:
            text = decimalDigits
        case 5...8:
            text = (String(letters[0...3]) + "-"
                + String(letters[4...7]))
                .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        case 9...12:
            text = (String(letters[ 0...3 ]) + "-"
                + String(letters[ 4...7 ]) + "-"
                + String(letters[8...11]))
                .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        case 13...16:
            text = (String(letters[ 0...3 ]) + "-"
                + String(letters[ 4...7 ]) + "-"
                + String(letters[8...11]) + "-"
                + String(letters[12...15]))
                .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        default:
            print(text)
            if decimalDigits.characters.count > 0 {
                text = String(text!.characters.prefix(19))
            }
        }
    }
}

Swift 3

class CustomField: UITextField {
    var stringValue: String { return text ?? "" }
    var decimalDigits: String {
        return stringValue
            .components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined(separator: "") ?? ""
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        addTarget(self, action: #selector(editindChanged(_:)), for: .editingChanged)
        keyboardType = .numberPad
        editindChanged(self)
    }
    func editindChanged(_ sender: UITextField) {
        let letters = Array(decimalDigits.padding(toLength: 16, withPad: " ", startingAt: 0).characters)
        switch decimalDigits.characters.count {
        case 1...4:
            text = decimalDigits
        case 5...8:
            text = (String(letters[0...3]) + "-"
                  + String(letters[4...7]))
                  .trimmingCharacters(in: .whitespaces)
        case 9...12:
            text = (String(letters[ 0...3 ]) + "-"
                  + String(letters[ 4...7 ]) + "-"
                  + String(letters[8...11]))
                  .trimmingCharacters(in:. whitespaces)
        case 13...16:
            text = (String(letters[ 0...3 ]) + "-"
                + String(letters[ 4...7 ]) + "-"
                + String(letters[8...11]) + "-"
                + String(letters[12...15]))
                .trimmingCharacters(in: .whitespaces)
        default:
            print(text)
            if decimalDigits.characters.count > 0 {
                text = String(text!.characters.prefix(19))
            }
        }
    }
}